Insert uppercase spaces in a string

Pretty basic problem, but hard to get into acceptable form:

I want to convert a string by inserting a space every 3 spaces, e.g.

"123456789" โ†’ "123 456 789"

"abcdefgh" โ†’ "abc def gh"

My code is currently

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 someone provide a more elegant solution?

+4
source share
4 answers

You can do this using a regex:

 "abcdefgh".replaceAll(".{3}", "$0 ") 
+10
source

You can use printf or String.format as follows:

  builder.append(String.format("%4s", threeDigitString)); 

Additional information on formatted pins / strings in the API .

+3
source

This does not put a space if already there:

 "abcdef gh".replaceAll("\\s*(..[^ ])\\s*", "$1 "); // --> "abc def gh" 
+1
source

replaceAll looks best, but if you consider a number like 12345, it will be converted to 123 45. But in numbers I think it should be 12 345

+1
source

All Articles