1

I want to basically to do this:

String secondString = firstString.trim().replaceAll(" +", " ");

Or replace all the multiple spaces in my string, with just a single space. However, is it possibly to do this without regex like I am doing here?

Thanks!

1
  • Java has a replace() method for strings that will find a given string and replace it with another string. Generally, we expect you to at least make a try at programming something before asking a question . . . then we will make suggestions from there. Commented Feb 15, 2020 at 19:44

1 Answer 1

1

However, is it possibly to do this without regex like I am doing here?

Yes. The regular expression is clear and easy to read, so I would probably use that; but you could use a nested loop, a StringBuilder and Character.isWhitespace(char) like

StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstString.length(); i++) {
    sb.append(firstString.charAt(i));
    if (Character.isWhitespace(firstString.charAt(i))) {
        // The current character is white space, skip characters until 
        // the next character is not.
        while (i + 1 < firstString.length() 
                    && Character.isWhitespace(firstString.charAt(i + 1))) {
            i++;
        }
    }
}
String secondString = sb.toString();

Note: This is a rare example of a nested loop that is O(N); the inner loop modifies the same counter as the outer loop.

Sign up to request clarification or add additional context in comments.

Comments

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.