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
(?=\\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.(?= ) means look ahead for a space, while (?=\\s) means look ahead for any white-space character.
String str2 = str.trim().replaceAll("\\s+", " ").because sometimes, larger trailing spaces would be trimmed in one shot!