0

I know how loops work but I wasn't sure how I could check the last index of the string I am iterating over in this case. Here is an example:

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
 }
ProgrammingCuber
  • 307
  • 3
  • 12
  • What do you mean, the index of the word in the array of words, or the index of the substring inside the original string? – khelwood Aug 01 '17 at 12:26
  • 1
    don't use the `foreach` loop, but a `for` instead – Lino Aug 01 '17 at 12:27
  • [Take a look at this](https://stackoverflow.com/questions/477550/is-there-a-way-to-access-an-iteration-counter-in-javas-for-each-loop) – bracco23 Aug 01 '17 at 12:27

2 Answers2

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
}
Aubin
  • 13,790
  • 8
  • 55
  • 78
0

You can use a counter..?

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
 }

If you mean the index of the starting character you are looking into something like this

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
 }
Murat Karagöz
  • 26,294
  • 9
  • 70
  • 97