当我打印出arraylist的索引时,如何删除最后一个逗号

List list1 = new ArrayList(words.length); List list2 = new ArrayList(word.length); for(String x: list1){ for(String y: list2){ if(x.equalsIgnoreCase(y)){ System.out.print(list1.indexOf(x) +" "+ ","); } } } 

对于这个function,运行之后,输出将是2,5,7 …. 9,我的问题是如何删除最后一个逗号?

我会在开头打印逗号,类似这样 –

 boolean first = true; for(String x: list1){ for(String y: list2){ if(x.equalsIgnoreCase(y)){ if (first) { first = false; } else { System.out.print(", "); // <-- or " ," if you prefer. } System.out.print(list1.indexOf(x)); } } } 

您将不得不弄清楚最后一个项目的打印时间。

您可以通过首先遍历列表并确定最后一个逗号应该在哪里来执行此操作,或者您可以使用StringBuilder构建整个String,然后在完成后使用逗号。

或者,除了第一个单词之外,您可以在单词之前添加逗号。

一种解决方案是使用循环来控制索引:

 int i,j; for(i = 0;i < x.size();i++){ for(j = 0;j < y.size() - 1; j++){ if(list1.get(i).equalsIgnoreCase(list2.get(j))) { System.out.print(list1.indexOf(x) +" "+ ","); } } if(list1.get(i).equalsIgnoreCase(list2.get(j))) { System.out.print(list1.indexOf(x)); } } 

使用Iterator检查列表中是否还有下一个元素。

 System.out.print(list1.indexOf(x) +" "); if(itr.hasNext()) { System.out.print(" ,"); // print the comma if there still elements } 

为了完整起见,这里是Java 8:

 final String joined = list1.stream(). flatMap(s -> list2.stream().filter(y -> s.equalsIgnoreCase(y))). mapToInt(s -> list1.indexOf(s)). mapToObj(Integer::toString). collect(Collectors.joining(", ")); 

您可以在构建字符串后删除最后一个逗号

构建字符串:

 StringBuilder output = new StringBuilder(); for(String x: list1){ for(String y: list2){ if(x.equalsIgnoreCase(y)){ output.append(list1.indexOf(x) +" "+ ","); } } } 

删除最后一个逗号打印:

 System.out.println(output.substring(0, output.lastIndexOf(","))); 
 str = str.replaceAll(", $", ""); 

这很容易,这样做:

 Boolean b = false; for(String x: list1){ for(String y: list2){ if(x.equalsIgnoreCase(y)){ System.out.print((b ? "," : "") + list1.indexOf(x)); b = true; } } }