String Traversals with Loops
Part of: Iteration
Walking Through a String A String traversal visits each character of a String one at a time using a loop. The two key tools are length() (the number of characters) and charAt(i) (the character at index i). Valid indices run from 0 to length() - 1. Mind the Boundary Notice the condition is i < s.length(), not <=. Using <= would call charAt(s.length()), which throws a StringIndexOutOfBoundsException because that index does not exist. This is the off-by-one rule from earlier applied to text. Common Traversal Patterns - Counting characters that match a rule (such as vowels). - Building a new String: result += s.charAt(i); accumulates characters. - Searching for a particular character. Reversing a String Traversing backward is just as easy, start at the last index and count down: Here the accumulator pattern and a String traversal combine. Because a char can be compared with == and concatenated with +, loops over text feel almost identical to loops over numbers, only the bounds and the access method change.
Challenge: Count Vowels