Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert padding whitespace into string

Tags:

java

string

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?

like image 612
Johannes Charra Avatar asked Jun 22 '11 10:06

Johannes Charra


1 Answers

You can do this using a regular expression:

"abcdefgh".replaceAll(".{3}", "$0 ")
like image 175
wjans Avatar answered Oct 18 '22 07:10

wjans