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();
oventarb
  • 1
  • 1
  • 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.... – Davio Feb 19 '15 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! – Maheswaran Ravisankar Feb 19 '15 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). – SubOptimal Feb 19 '15 at 12:04

1 Answers1

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
Jurgen
  • 2,138
  • 12
  • 18
  • Thank you. But more complex version will not work there is any any tabs or line feeds in the middle of the string. – oventarb Feb 20 '15 at 09:01
  • 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. – Jurgen Feb 20 '15 at 16:07
  • (?=\\s) will change to tabulation or line feed or something else. But I want change to space, not any other whitespace. – oventarb Feb 20 '15 at 17:41
  • (?=\\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. – Jurgen Feb 23 '15 at 07:46