How to remove the last comma when I print out the index of arraylist

本小妞迷上赌 提交于 2019-11-29 18:05:28

I would print the comma at the start, something like this -

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

You're going to have to figure out when the last item has been printed.

You can either do this by iterating through the list first and figuring out where the last comma should be, or you can build the whole String using StringBuilder and then take the comma of when you're done.

Alternatively, you could put the comma before the word for every word except the first one.

One solution is using loops with control over indexes:

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

Use Iterator to check if there still next elements in your list.

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

Just for completeness, here it is in 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(", "));
bgth

You could simply remove the last comma after building the string

Build the string:

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

Print with last comma removed:

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

That's easy, do it this way:

Boolean b = false;
for(String x: list1){
    for(String y: list2){
        if(x.equalsIgnoreCase(y)){
           System.out.print((b ? "," : "") + list1.indexOf(x));
           b = true;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!