Reputation: 29923
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?
Upvotes: 5
Views: 11429
Reputation: 11
The replaceAll
looks to be the best, but if you consider a number like 12345 it would be converted to 123 45. But in numbers I believe it should be 12 345
Upvotes: 1
Reputation: 425033
This doesn't put a space if there's already one there:
"abcdef gh".replaceAll("\\s*(..[^ ])\\s*", "$1 "); // --> "abc def gh"
Upvotes: 1
Reputation: 10115
You can do this using a regular expression:
"abcdefgh".replaceAll(".{3}", "$0 ")
Upvotes: 10
Reputation: 4469
You can use printf
or String.format
like so:
builder.append(String.format("%4s", threeDigitString));
More information on formatted output/strings in the API.
Upvotes: 3