java - 打印出数组中的元素,元素之间使用逗号

我正在打印 ArrayList 中的元素,并且希望在除最后一个单词之外的每个单词之后有一个逗号。

现在,我正在这样做:

for (String s : arrayListWords) {
    System.out.print(s + ", ");
}

它打印出这样的单词:

one, two, three, four,

问题是最后一个逗号。我该如何解决?

最佳答案

如果存在,则单独打印第一个单词。然后先将模式打印为逗号,然后是下一个元素。

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]);
}

使用 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());
}

https://stackoverflow.com/questions/18279622/

相关文章:

formatting - 不显示文化的本国货币时的正确货币格式

c# - 对混合数字和字符串进行排序

c - printf 格式(%d 与 %u)

php - 使用 PHPExcel 以文本格式读取数字

android - 在用户语言环境中显示日期和时间

c# - C++ 格式化,如 Visual Studio C# 格式化

text - LaTeX - 更改文档的字体大小,但在序言中,而不是文档类?

r - 通过符号在ggplot2中设置特定的填充颜色

formatting - Go 语言中的打印格式列表

python - 格式化复数