java 将填充空格插入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6438319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:53:20  来源:igfitidea点击:

Insert padding whitespace into string

javastring

提问by Johannes Charra

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

我想通过每 3 个空格插入一个填充来转换字符串,例如

"123456789" -> "123 456 789"

“123456789”->“123 456 789”

"abcdefgh" -> "abc def gh"

"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?

谁能提供更优雅的解决方案?

回答by wjans

You can do this using a regular expression:

您可以使用正则表达式执行此操作:

"abcdefgh".replaceAll(".{3}", "
 builder.append(String.format("%4s", threeDigitString));
")

回答by dcn

You can use printfor String.formatlike so:

您可以使用printfString.format喜欢这样:

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

More information on formatted output/strings in the API.

有关API 中格式化输出/字符串的更多信息。

回答by Bohemian

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

如果已经有一个空间,这不会放置一个空间:

##代码##

回答by naveinaustin

The replaceAlllooks 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

replaceAll看起来是最好的,但如果你考虑一些像12345将它转换为123 45.但数字我相信它应该是12 345