java中如何在字符串中填充空格?

发布于 2024-12-09 17:00:12 字数 635 浏览 7 评论 0原文

可能的重复:
如何在 Java 中填充字符串?

我有一个我的 method1() 返回各种大小的字符串,并且我想在固定空间中显示该字符串(例如长度为 50 个字符),如果长度大于 50 个字符,但不确定是什么,我可以使用 String.substring()如果字符串长度为少于50个字符,我该如何实现?

for example my method1() return (in different call) :
John
Michael
J
Ab

While method2() return :
first
Second
Third

我想打印结果,就像

John                 First
Michael              Second
J                    Third
Ab                   Forth

我不想使用除空格之外的任何其他字符一样。

Possible Duplicate:
How can I pad a String in Java?

I have a stuation in which my method1() return the string of various size and I want to display the string in a fix space (say length 50 character) I can use String.substring() if the length is greater than 50 character but not sure what to do if the string length is less than 50 character , how can I achieve that ?

for example my method1() return (in different call) :
John
Michael
J
Ab

While method2() return :
first
Second
Third

and I want to print the result like

John                 First
Michael              Second
J                    Third
Ab                   Forth

I don't want to use any other character except space.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花期渐远 2024-12-16 17:00:13
public String toFixedLength(String str, int sz) {      
  String ret;
  int len = str.length();

  if (len == sz) {
    ret = str;
  } else if (len > sz) {
    ret = str.substring(0, sz);
  } else { // len < sz
    StringBuilder sb = new StringBuilder(str);

    char[] ch = new char[sz - len];
    Arrays.fill(ch, ' ');
    sb.append(ch);
    ret = sb.toString();
  }

  return ret;
}
public String toFixedLength(String str, int sz) {      
  String ret;
  int len = str.length();

  if (len == sz) {
    ret = str;
  } else if (len > sz) {
    ret = str.substring(0, sz);
  } else { // len < sz
    StringBuilder sb = new StringBuilder(str);

    char[] ch = new char[sz - len];
    Arrays.fill(ch, ' ');
    sb.append(ch);
    ret = sb.toString();
  }

  return ret;
}
遥远的她 2024-12-16 17:00:13

只需检查字符串的 length() 并添加所需数量的空格(例如,在一个循环中)

Just check the string's length() and add the required number of spaces (say, in a cycle)

美人骨 2024-12-16 17:00:13

如果你有一个长度小于五十个字符的字符串并且你想将其填充,你可以这样做:

int temp = yourstring.length

for(int i = 0; i < (50-temp); i++){
  yourstring = yourstring + " ";
}

我很确定这会起作用,如果 yourstring 是你要填充的字符串并且你还没有之前在您的代码中没有使用 i 作为整数。这样你只需要使用空间。

If you have a string with a length of less than fifty characters and you want to pad it out, you could just do:

int temp = yourstring.length

for(int i = 0; i < (50-temp); i++){
  yourstring = yourstring + " ";
}

I'm pretty sure that'd work, if yourstring is the string you're trying to pad and you haven't used i as an integer previously in your code. This way you only have to use space.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文