Java 有什么方法可以在不使用 for 循环的情况下打印 String 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3481491/
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
Is there any way I can print String array without using for loop?
提问by priyank
Is there any function in java like toString() to print a String array?
java中有没有像 toString() 这样的函数来打印字符串数组?
This is a silly question but I want to know if there is any other way than writing a for loop.
这是一个愚蠢的问题,但我想知道除了编写 for 循环之外是否还有其他方法。
Thanks.
谢谢。
采纳答案by Mike
String[] array = { "a", "b", "c" };
System.out.println(Arrays.toString(array));
回答by Steve B.
String[] values= { ... }
System.out.println(Arrays.asList(values));
回答by David Z
There is the Arrays.toString()
method, which will convert an array to a string representation of its contents. Then you can pass that string to System.out.println
or whatever you're using to print it.
有一个Arrays.toString()
方法,它将一个数组转换为其内容的字符串表示。然后你可以将该字符串传递给System.out.println
或任何你用来打印它的东西。
回答by adu
I think you are looking for
我想你正在寻找
System.out.printf(String fmtString, Object ... args)
Where you specify the format of the output using some custom java markup (this is the only part you need to learn). The second parameter is the object, in your case, the array of strings.
您可以在其中使用一些自定义 java 标记指定输出格式(这是您需要学习的唯一部分)。第二个参数是对象,在您的情况下,是字符串数组。
More information: Using Java's Printf Method
更多信息: 使用 Java 的 Printf 方法
回答by Steven Schlansker
If you need a bit more control over the string representation, Google Collections Joinerto the rescue!
如果您需要对字符串表示有更多的控制,Google Collections Joiner可以帮助您!
String[] myArray = new String[] {"a", "b", "c"};
String joined = Joiner.on(" + ").join(myArray);
// => "a + b + c"