Java 打印出数组中的元素,除最后一个单词外的元素之间用逗号隔开
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18279622/
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
Print out elements from an array with a comma between elements except the last word
提问by Eri.
I am printing out elements from an array list and want to have a comma between each word except the last word. Right now I am doing it like this:
我正在从数组列表中打印出元素,并希望在除最后一个单词之外的每个单词之间使用逗号。现在我是这样做的:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
As you understand it will print out the words like this: one, two, three, four,
and the problem is the last comma, how do I solve this? All answers appreciated!
如您所知,它会打印出这样的单词:one, two, three, four,
问题是最后一个逗号,我该如何解决?所有答案表示赞赏!
采纳答案by Sotirios Delimanolis
Print the first word on its own if it exists. Then print the pattern as comma first, then the next element.
如果存在,则自行打印第一个单词。然后首先将模式打印为逗号,然后是下一个元素。
if (arrayListWords.length >= 1) {
System.out.print(arrayListWords[0]);
}
// note that i starts at 1, since we already printed the element at index 0
for (int i = 1; i < arrayListWords.length, i++) {
System.out.print(", " + arrayListWords[i]);
}
With a List
, you're better off using an Iterator
使用 a List
,您最好使用Iterator
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
回答by Boris the Spider
You can use an Iterator
on the List
to check whether there are more elements.
您可以使用Iterator
onList
来检查是否还有更多元素。
You can then append the comma only if the current element is not the last element.
只有当当前元素不是最后一个元素时,您才能附加逗号。
public static void main(String[] args) throws Exception {
final List<String> words = Arrays.asList(new String[]{"one", "two", "three", "four"});
final Iterator<String> wordIter = words.iterator();
final StringBuilder out = new StringBuilder();
while (wordIter.hasNext()) {
out.append(wordIter.next());
if (wordIter.hasNext()) {
out.append(",");
}
}
System.out.println(out.toString());
}
However it is much easier to use a 3rd party library like Guavato do this for you. The code then becomes:
然而,使用像Guava这样的 3rd 方库来为你做这件事要容易得多。然后代码变成:
public static void main(String[] args) throws Exception {
final List<String> words = Arrays.asList(new String[]{"one", "two", "three", "four"});
System.out.println(Joiner.on(",").join(words));
}
回答by Ruchira Gayan Ranaweera
You can try this
你可以试试这个
List<String> listWords= Arrays.asList(arrayListWords); // convert array to List
StringBuilder sb=new StringBuilder();
sb.append(listWords);
System.out.println(sb.toString().replaceAll("\[|\]",""));
回答by sanbhat
While iterating, you can append the String s
to the StringBuilder
and at the end, you can delete the last 2 chars which is an extra ,
and a space (res.length() -2
)
迭代时,您可以将 附加String s
到StringBuilder
最后,您可以删除最后 2 个字符,这是一个额外的字符,
和一个空格 ( res.length() -2
)
StringBuilder res = new StringBuilder();
for (String s : arrayListWords) {
res.append(s).append(", ");
}
System.out.println(res.deleteCharAt(res.length()-2).toString());
回答by akkerman
You could use a standard function in the java.util package and remove the block quotes at start and end.
您可以使用 java.util 包中的标准函数并删除开头和结尾的块引号。
String str = java.util.Arrays.toString(arrayListWords);
str = str.substring(1,str.length()-1);
System.out.println(str);
回答by Rohit
Just use the toString() method.
只需使用 toString() 方法。
String s = arrayListWords.toString();
System.out.println(s);
//This will print it like this: "[one, two, three, four]"
//If you want to remove the brackets you can do so easily. Just change the way you print.
回答by Mav
I would write it this way:
我会这样写:
String separator = ""; // separator here is your ","
for (String s : arrayListWords) {
System.out.print(separator + s);
separator = ",";
}
If arrayListWords has two words, it should print out A,B
如果 arrayListWords 有两个单词,它应该打印出 A,B
回答by Camilo Silva
Using Java 8 Streams:
使用 Java 8 流:
Stream.of(arrayListWords).collect(Collectors.joining(", "));
回答by Simple-Solution
Here is what I come up with:
这是我想出的:
String join = "";
// solution 1
List<String> strList = Arrays.asList(new String[] {"1", "2", "3"});
for(String s: strList) {
int idx = strList.indexOf(s);
join += (idx == strList.size()-1) ? s : s + ",";
}
System.out.println(join);
// solution 2
join = "";
for(String s: strList) {
join += s + ",";
}
join = join.substring(0, join.length()-1);
System.out.println(join);
// solution 3
join = "";
int count = 0;
for(String s: strList) {
join += (count == strlist.size()-1) ? s: s + ",";
count++;
}
System.out.println(join);
off course we can utalise StringBuilder
but of all solutions, I like @Mav
answer as it's more efficient and clean.
当然,我们可以使用,StringBuilder
但在所有解决方案中,我喜欢@Mav
answer,因为它更高效、更干净。
回答by Lital Kolog
With Java 8 it got much easier, no need for 3rd parties -
有了 Java 8,它变得更容易了,不需要第三者——
final List<String> words = Arrays.asList("one", "two", "three", "four");
Optional<String> wordsAsString = words.stream().reduce((w1, w2) -> w1 + "," + w2);
wordsAsString.ifPresent(System.out::println);