我知道循环是如何工作的但是我不确定如何检查我在这种情况下迭代的字符串的最后一个索引。这是一个例子:
String words = "Apple gum fruit red orange triangle";
for(String foo : words.split("\\s+"){
//How would I get the index of foo at any given point in the loop
}
答案 0 :(得分:2)
String sentence = "Apple gum fruit red orange triangle";
String[] words = sentence.split("\\s+");
for( int i = 0; i < words.length; ++i ) {
String foo = words[i];
// i is the index
}
答案 1 :(得分:0)
您可以使用计数器..?
String words = "Apple gum fruit red orange triangle";
int counter = 0;
for(String foo : words.split("\\s+"){
System.out.println(counter);
counter++;
//How would I get the index of foo at any given point in the loop
}
如果你的意思是起始角色的索引,你正在寻找类似这样的东西
String words = "Apple gum fruit red orange triangle";
int index = 0;
for(String foo : words.split("\\s+"){
System.out.println(index);
index += foo.length() +1; // to dismiss the whitespace
//How would I get the index of foo at any given point in the loop
}