Reputation: 1
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();
Upvotes: 0
Views: 119
Reputation: 2154
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
Upvotes: 1