Pretty basic problem, but difficult to get into an acceptable form:
I want to transform a string by inserting a padding every 3 whitespaces like
"123456789" -> "123 456 789"
"abcdefgh" -> "abc def gh"
My code currently is
public String toSpaceSeparatedString(String s) {
if (s == null || s.length() < 3) {
return s;
}
StringBuilder builder = new StringBuilder();
int i;
for (i = 0; i < s.length()-3; i += 3) {
builder.append(s.substring(i, i+3));
builder.append(" ");
}
builder.append(s.substring(i, s.length()));
return builder.toString();
}
Can anyone provide a more elegant solution?
You can do this using a regular expression:
"abcdefgh".replaceAll(".{3}", "$0 ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With