在 Java 中格式化字符串输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5254728/
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 String Output in Java
提问by Michael
I am trying to format a string in the output differently than the way it is already formatted within my program. It's a pizza ingredient menu and in the bulk of the program whenever it's outputted it is formatted right with a "\n" between the ingredients so as to create a list "feel". However, in the final menu where the users choice is displayed, I want to also put the ingredient list because the user can customize which ingredients are on their pizza. This is difficult with a vertical list of the ingredients because it can make the final output really long if the user has more than one pizza. I'm trying to find out if there's a way I can take the same string that was formatted for vertical display and display it horizontally with a comma between the ingredients instead of "\n". Any ideas? Or should I just create a new string that's formatted the way I want with the information I need?
我试图在输出中格式化一个字符串,而不是它在我的程序中已经格式化的方式。这是一个比萨配料菜单,在程序的大部分内容中,无论何时输出,它都会在配料之间使用“\n”进行格式化,以创建一个“感觉”列表。但是,在显示用户选择的最终菜单中,我还想放置成分列表,因为用户可以自定义披萨上的成分。这对于垂直的成分列表来说很困难,因为如果用户有多个比萨饼,它会使最终输出非常长。我试图找出是否有一种方法可以采用为垂直显示格式化的相同字符串,并在成分之间使用逗号而不是“\n”来水平显示它。有任何想法吗?或者我应该只创建一个新的字符串,用我需要的信息按照我想要的方式格式化?
String i1 = "Pepperoni", i2 = "Sausage", i3 = "Canadian Bacon";
String ingredients = i1 + "\n" + i2 + "\n" + i3 + "\n";
System.out.print(ingredients);
System.out.printf("Your pizza includes only these ingredients: %s", ingredients);
The first System.out.print(ingredients) is similar to the code that I have that prints the ingredients vertically throughout the program so that it's easily readable to the user.
第一个 System.out.print(ingredients) 类似于我在整个程序中垂直打印成分的代码,以便用户轻松阅读。
The second System.out.print(...) is what I'm trying to format so that the list of ingredients displays horizontally.
第二个 System.out.print(...) 是我试图格式化的内容,以便成分列表水平显示。
回答by dml
String i1 = "Pepperoni", i2 = "Sausage", i3 = "Canadian Bacon";
String ingredients = i1 + "\n" + i2 + "\n" + i3;
System.out.println(ingredients);
System.out.println("Your pizza includes only these ingredients: " + ingredients.replace("\n", ", ")
回答by I82Much
String s = "hi\nthere";
s.replaceAll("\n", ","); // (returns "hi,there")
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
回答by Stephen C
I'd have thought that this was clearer:
我原以为这更清楚:
String i1 = "Pepperoni", i2 = "Sausage", i3 = "Canadian Bacon";
System.out.printf("%s\n%s\n%s\n", i1, i2, i3);
System.out.printf("Your pizza includes ingredients: %s %s %s", i1, i2, i3);
The point is, if you are going to use printf
at all, you may as well make use of its ability to join strings together.
关键是,如果您打算使用它printf
,您不妨利用它的功能将字符串连接在一起。
From your comment, I take it that the number of ingredients is variable. If that's the case, using printf
for formatting the "list" (like I did above) won't cut it. Instead you need a helper method like this:
根据您的评论,我认为成分的数量是可变的。如果是这种情况,printf
用于格式化“列表”(就像我上面所做的那样)不会削减它。相反,您需要一个像这样的辅助方法:
public static String join(String separator, Object[] things) {
StringBuilder sb = new StringBuilder();
for (Object thing : things) {
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(thing);
}
return sb.toString();
}
Then ...
然后 ...
Object[] ingredients = new Object[]{i1, i2, i3}; // ... or a dynamic sided array
System.out.print(join("\n", ingredients));
System.out.println("Your pizza includes ingredients: " + join(" ", ingredients));
I claim that this is more general (works with variable size arrays), easier to understand, and possibly more efficient than other suggestions.
我声称这比其他建议更通用(适用于可变大小的数组),更容易理解,并且可能更有效。
(The join
helper method exists in various guises in a number of class libraries; e.g. in the Apache Commons StringUtils
class. )
(join
辅助方法以各种形式存在于许多类库中;例如在 Apache CommonsStringUtils
类中。)
回答by necromancer
replacing \n with , is rookie programmer style and will come back to bite you soon. try this instead for the comma part (and do the \n part manually like you are already doing):
用 替换 \n 是菜鸟程序员的风格,很快就会回来咬你。试试这个来代替逗号部分(并像你已经在做的那样手动执行 \n 部分):
String [] ingredients = {"Pepperoni", "Sausage", "Canadian Bacon"};
String almost_there = Arrays.deepToString(ingredients);
String there = almost_there.substring(1, almost_there.length() - 1);
System.out.printf("Your pizza includes ingredients: ", there);