String Length and Bounds Checking
What you'll learn: How to use the length property to safely determine how many characters are in a string and avoid crashing your program when accessing individual characters.
Why String Length Matters
Remember that strings are arrays of characters. Just like arrays have a specific number of elements, every string has a specific number of characters — this is called its length. Before you access a character at a particular index, you need to know if that index actually exists.
Think of a string like a train with numbered cars. If the train has 5 cars (numbered 0-4), trying to board car #7 would be impossible — you'd step off the platform into thin air!
Getting the Length
Most programming languages provide a way to check a string's length. This tells you how many characters the string contains. For a string name with value "Alice", the length is 5.
Valid indices for this string are 0 through 4 (length minus one), because indexing starts at zero.
Bounds Checking: Staying Safe
Bounds checking means verifying that an index is within the valid range before accessing it. Valid indices run from 0 to length - 1.
Accessing an index outside this range causes an out-of-bounds error — your program might crash or produce garbage data. This is one of the most common beginner mistakes!
Before accessing name[i], always ensure i >= 0 and i < length.
Practical Application
When traversing a string with a loop, use the length to control iteration. Your loop should run while the index is less than the string's length — never equal to it or beyond.
Key Takeaway: Always check a string's length before accessing characters by index, and ensure your index stays between 0 and length - 1 to avoid out-of-bounds errors.