java中如何在字符串中填充空格?
可能的重复:
如何在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需检查字符串的
length()
并添加所需数量的空格(例如,在一个循环中)Just check the string's
length()
and add the required number of spaces (say, in a cycle)如果你有一个长度小于五十个字符的字符串并且你想将其填充,你可以这样做:
我很确定这会起作用,如果 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:
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.