在java中格式化字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1899138/
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
Formatting strings in java
提问by Surjya Narayana Padhi
I am reading the serial buffer with readLine() method. The string returned by readLine() is in the format "str1 : str2". In a while loop when I use readLine() number of times for a response of serial port command I get weird output like this :
我正在使用 readLine() 方法读取串行缓冲区。readLine() 返回的字符串的格式为“str1 : str2”。在 while 循环中,当我多次使用 readLine() 响应串行端口命令时,我得到如下奇怪的输出:
String1 : string1
SString11 : String2
StringString2 : String23
String4 : String5
But I need the output formatted as below
但我需要如下格式的输出
String1 : string1
SString11 : String2
StringString2 : String23
String4 : String5
I used the split method on string and get the two strings separated with delimiter as ':'. But now I need to append the String1 with spaces to align all the colons.
我在字符串上使用了 split 方法,并将两个字符串用分隔符分隔为 ':'。但现在我需要用空格附加 String1 以对齐所有冒号。
I am sorry If my problem explanation is weird. But If anybody understood the problem can you please suggest how to do it?
如果我的问题解释很奇怪,我很抱歉。但如果有人理解这个问题,你能建议怎么做吗?
采纳答案by TofuBeer
Take a look at System.out.printf
回答by Vijay Mathew
The easiest way to achieve this is to use System.out.format(). This lets you use C printfstyle format specifiers. An example:
实现这一点的最简单方法是使用System.out.format()。这使您可以使用 C printf样式的格式说明符。一个例子:
System.out.format("%-5s:%10s\n", "Name", "Nemo");
System.out.format("%-5s:%10d\n", "Age", 120);
This will output:
这将输出:
Name : Nemo
Age : 120
Also see documentation for the Formatterclass to learn more about the format string syntax.
另请参阅Formatter类的文档以了解有关格式字符串语法的更多信息。
回答by Mayuresh
System.out.format("%30s : %s", str1, str2);
System.out.format("%30s : %s", str1, str2);
Will print the first string with a fixed width of 30 characters.
将打印固定宽度为 30 个字符的第一个字符串。