我使用StringBuilder在记录之间显示逗号,但在最后记录结束时也使用逗号
如何控制?我不想在最后一张唱片的末尾看到逗号 - 因为它没用了
for (int i = 0; i < arrayList.size(); i++) {
String name = arrayList.get(i).getName();
int price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
stringBuilder.append(" - "+price+",");
}
stringFinal = stringBuilder.toString();
答案 0 :(得分:7)
使用Java 8时不需要任何检查。您只需使用StringJoiner
(或String.join()
)。
StringJoiner joiner = new StringJoiner(",");
for (int i = 0; i < arrayList.size(); i++) {
String name = arrayList.get(i).getName();
int price = arrayList.get(i).getPrice();
joiner.add(strName + " - " + price);
}
String joinedString = joiner.toString();
您可以利用Stream
API(感谢@Sasha)使其更加清洁:
String joinedString = String.join(",", list.stream().map(
e -> e.getName() + " - " + e.getPrice()).collect(Collectors.toList()));
答案 1 :(得分:4)
添加对最后一项的检查。
if (i < arrayList.size() - 1) {
stringBuilder.append(" - "+price+",");
} else {
stringBuilder.append(" - "+price);
}
或:
stringBuilder.append(" - "+price);
if (i < arrayList.size() - 1) {
stringBuilder.append(",");
}
答案 2 :(得分:1)
int index = stringBuilder.lastIndexOf(",");
if (index != -1){
stringBuilder.replace(index, index+1, "");
}
String stringFinal = stringBuilder.toString();
答案 3 :(得分:0)
或循环直到大小 - 1然后在没有逗号的病房后添加最后一个元素。
int i = 0, price = 0;
String name = null;
for (i = 0; i < arrayList.size() - 1; i++) {
name = arrayList.get(i).getName();
price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
stringBuilder.append(" - "+price+",");
}
name = arrayList.get(i).getName();
price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
stringBuilder.append(" - "+price);
stringFinal = stringBuilder.toString();
答案 4 :(得分:0)
for (int i = 0; i < arrayList.size(); i++) {
String name = arrayList.get(i).getName();
int price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
if(i== arrayList.size()-1)
stringBuilder.append(" - "+price);
else
stringBuilder.append(" - "+price+",");
}
stringFinal = stringBuilder.toString();
答案 5 :(得分:0)
不要把它放在最后,你可以在前面写出来,如: -
String name = arrayList.get(0).getName();
int price = arrayList.get(0).getPrice();
stringBuilder.append(strName).append(" - "+price);
for (int i = 1; i < arrayList.size(); i++) {
name = arrayList.get(i).getName();
price = arrayList.get(i).getPrice();
stringBuilder.append(","+strName).append(" - "+price);
}
stringFinal = stringBuilder.toString();
答案 6 :(得分:0)
您可以删除最后一个字符:
stringBuilder.deleteCharAt(stringBuilder.length()-1);
stringFinal = stringBuilder.toString();
这将是最简单的解决方案。