问题
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) +" "+ ",");
}
}
}
For this function, after run it, the output will be 2,5,7....9, My question is how to remove the last comma?
回答1:
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));
}
}
}
回答2:
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.
回答3:
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));
}
}
回答4:
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
}
回答5:
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(", "));
回答6:
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(",")));
回答7:
str = str.replaceAll(", $", "");
回答8:
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;
}
}
}
来源:https://stackoverflow.com/questions/22664146/how-to-remove-the-last-comma-when-i-print-out-the-index-of-arraylist