oventarb
oventarb

Reputation: 1

More efficient line of code in Java

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

Answers (1)

Jurgen
Jurgen

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

Related Questions