0

I work with strings in my programs for many times.

Is there a way to do this line of Java code more efficient:

String str2 = str.replaceAll("\\s+", " ").trim();
3
  • I don't really think so (other than hidden away in a commons library) and by the way, you're only removing spaces in the middle, not tabs, linefeeds, etc, I think.... Commented Feb 19, 2015 at 11:56
  • 4
    Trim first and then replace like String str2 = str.trim().replaceAll("\\s+", " "). because sometimes, larger trailing spaces would be trimmed in one shot! Commented Feb 19, 2015 at 11:59
  • Where the strings are comming from? If they are the result of a database query, I would try to let the database do the work (at least as much as possible). Commented Feb 19, 2015 at 12:04

1 Answer 1

1

You could try using a pre compiled pattern:

private Pattern p = Pattern.compile( "\\s+" );

And then use it like so:

str2 = p.matcher( str.trim() ).replaceAll( " " );

A more complex version that doesn't require trimming:

private Pattern p = Pattern.compile( "^\\s+|\\s+(?= )|\\s+$" );

str2 = p.matcher( str ).replaceAll( "" );  // no space
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. But more complex version will not work there is any any tabs or line feeds in the middle of the string.
Sorry, you can try (?=\\s) instead of (?= ), but I think the simpler version would be better. You can also try moving the trim to after the replaceAll and see how that works - performance wise.
(?=\\s) will change to tabulation or line feed or something else. But I want change to space, not any other whitespace.
(?=\\s) isn't for the replacement character, its part of the pattern being looked for. (?= ) means look ahead for a space, while (?=\\s) means look ahead for any white-space character.

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.