2

I was working on some string formatting, and I was curious if I was doing it the most efficient way.

Assume I have a String Array:

String ArrayOne[] = {"/test/" , "/this/is/test" , "/that/is/" "/random/words" }

I want the result Array to be

String resultArray[] = {"test", "this_is_test" , "that_is" , "random_words" }

It's quite messy and brute-force-like.

for(char c : ArrayOne[i].toCharArray()) {
      if(c == '/'){
            occurances[i]++;
      }
   }

First I count the number of "/" in each String like above and then using these counts, I find the indexOf("/") for each string and add "_" accordingly.

As you can see though, it gets very messy.

Is there a more efficient way to do this besides the brute-force way I'm doing?

Thanks!

1
  • Read up on the replace and replaceAll methods of the String class. Also learn how to use a regular expression to detect the beginning or the end of a String. Commented Oct 15, 2014 at 0:05

1 Answer 1

3

You could use replaceAll and replace, as follows:

String resultArray[] = new String[ArrayOne.length];
for (int i = 0; i < ArrayOne.length; ++i) {
    resultArray[i] = ArrayOne[i].replaceAll("^/|/$", "").replace('/', '_');
}

The replaceAll method searches the string for a match to the regex given in the first argument, and replaces each match with the text in the second argument.

Here, we use it first to remove leading and trailing slashes. We search for slashes at the start of the string (^/) or the end of the string (/$), and replace them with nothing.

Then, we replace all remaining slashes with underscores using replace.

9
  • did you see this "/test/" will be this "test"? Commented Oct 15, 2014 at 0:09
  • @KickButtowski And what is the problem with that?
    – Pshemo
    Commented Oct 15, 2014 at 0:12
  • @KickButtowski: yep, that's what the first replaceAll is for.
    – Mac
    Commented Oct 15, 2014 at 0:12
  • @Mac consider using replace('/', '_') instead of replaceAll("/", "_") to avoid regex engine.
    – Pshemo
    Commented Oct 15, 2014 at 0:12
  • @Pshemo: excellent point. Will update accordingly in a moment.
    – Mac
    Commented Oct 15, 2014 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.