【发布时间】:2020-02-05 08:56:19
【问题描述】:
在打印时删除数组最后一个元素中的逗号有什么建议吗?
public static void printList(String[] words, int count) {
for (int i=0; i < count; i++) {
System.out.print(words[i] + ",");
}
}
【问题讨论】:
标签: java
在打印时删除数组最后一个元素中的逗号有什么建议吗?
public static void printList(String[] words, int count) {
for (int i=0; i < count; i++) {
System.out.print(words[i] + ",");
}
}
【问题讨论】:
标签: java
我喜欢处理这个问题的一种方法是有条件地在前添加一个逗号,仅用于第二个单词:
public static void printList(String[] words, int count) {
for (int i=0; i < count; i++) {
if (i > 0) System.out.print(",");
System.out.print(words[i]);
}
}
你也可以构建你想要的输出字符串,然后去掉最后的逗号:
StringBuilder sb = new StringBuilder();
for (int i=0; i < count; i++) {
sb.append(words[i]).append(",");
}
String output = sb.toString().replaceAll(",$", "");
System.out.println(output);
【讨论】:
一种快速方法:
public static void printList(String[] words, int count) {
for(int i = 0; i < count; i++) {
System.out.print(words[i]);
if(i != count-1) System.out.print(",");
}
}
【讨论】: