Here's one which removes the entirety of the StringBuilder
operations you do. If on Java 8, simply use String.join(CharSequence delimiter, CharSequence... elements)
. In your case, delimiter
would be " "
, and elements
would be strArray
.
Final Code:
public static String sortString(String s){ String[] strArray = s.split("\\s+"); Arrays.sort(strArray); return String.join(" ", strArray); }
(A Java 8 3-liner solution, possibly a bit less complex than the one proposed by @Tunaki - 3 method calls here to 4 there).
And, since we are on Java 8 already, and you are concerned about performance and have really long 40-50 word String
s, try Arrays.parallelSort(Object[])
in place of Arrays.sort(Object[])
.