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();
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();
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