This will look for the given character in a string starting from the given startIndex.
If it finds any, returns its index position corresponding to that character inside the string.
str.length = 21
First time while loop,
i = 0
for the first time indexOf finds white space position at 4
No wonder why this code confuses you… it frankly confuses me too
Whenever you see black magic lines like while(true) it might be not worth to research and study such algorithm. If you need something to research, you can try this solution:
Normally, you have seen indexOf used passing a single argument to it like:
The above would return the index of the first character that is a space character.
There is an option of passing a second argument to indexOf. The second argument specifies at which index to start looking. If you do not pass a second argument to indexOf, it starts looking at index 0.
str.indexOf(' ', 3)
The above would return the index of the first character (starting at index 3) that is a space character. Keep in mind, that in any case where a space character is not found, the value -1 is returned.
str.indexOf(' ', i)
Putting everything explained so far, the above returns the index of the first character (starting at index i) that is a space character. If no space character is found at index i or after, then -1 is returned.