2014-03-26 57 views
0
List<String> list1 = new ArrayList<String>(words.length); 
List<String> list2 = new ArrayList<String>(word.length);  
for(String x: list1){ 
     for(String y: list2){ 
      if(x.equalsIgnoreCase(y)){ 
       System.out.print(list1.indexOf(x) +" "+ ","); 
      } 
     } 
    } 

索引对于这个功能,运行之后将其删除最后一个逗号,输出将是2,5,7 .... 9, 我的问题是如何删除最后一个逗号?如何当我打印出来的ArrayList

+1

的[移除循环打印输出JAVA最后一个逗号]可能重复(http://stackoverflow.com/questions/18297551/remove-last-comma -from-loop-printouts-java) –

+0

I [写下这个确切的代码](http://stackoverflow.com/a/22585042/2071828)。希望能帮助到你。 –

回答

2

我会在开始打印逗号,像这样 -

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)); 
     } 
    } 
} 
+0

谢谢艾略特,它的作品 – Mike

0

你将不得不弄清最后一个项目何时被打印。

您可以通过先遍历列表并确定最后一个逗号应该在哪里来完成此操作,也可以使用StringBuilder构建整个字符串,然后在完成时取出逗号。

或者,您可以在之前的逗号之前的每个单词除第一个单词外。

+0

你能修改我的代码来实现吗? – Mike

+0

Uhhhhhhhhhh没有。 –

+0

我做到了,谢谢。 – Mike

0

一种解决方案是在指数使用循环与控制:

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)); 
    } 
} 
+0

我本来想这太,但假设 列表1 = ABCDE 列表2 = ABEA 它会打印出类似“0,01,4” – Meow

0

使用Iterator检查是否还有下一个元素在你的清单中。

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

这很简单,做这种方式:

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

只是为了保持完整性,这是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(", ")); 
0

你可以简单地构建后删除最后一个逗号字符串

构建字符串:

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(","))); 
+0

你的代码的解释可能帮助OP。 – Dan

+0

感谢您的编辑。将在下次处理注释 – bgth

0
str = str.replaceAll(", $", ""); 
+0

请解释@Odaym – rjdkolb

+0

使用replaceAll匹配一个逗号,后跟'行结束符'(即$符号)replaceAll接受正则表达式 – Odaym