开发者

Insert padding whitespace into string

开发者 https://www.devze.com 2023-03-14 19:42 出处:网络
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

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 toSpaceSep开发者_运维知识库aratedString(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 ")


You can use printf or String.format like so:

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

More information on formatted output/strings in the API.


This doesn't put a space if there's already one there:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消