Strings Indexing, Length, and Traversal
Explore string manipulation fundamentals in C++. Understand zero-based indexing, character access methods, and how to determine string length. Learn different traversal techniques including forward, reverse, and indexed loops. Gain practical knowledge to navigate strings safely and efficiently while avoiding common errors.
We'll cover the following...
By now, you know that a string is an ordered sequence of characters stored contiguously in memory and that its structure is essentially identical to an array. It is a clean and simple idea, but an idea alone does not help you solve problems. The real question is how you actually work with a string once you have one. How do you reach into it and pull out a specific character? How do you know how many characters it contains? How do you move through it one step at a time? These are the basic operations that every string algorithm depends on, and getting comfortable with them is what turns the conceptual picture of strings into something you can actually use.
Indexing in strings
Each character in the string is associated with a specific position called an index. Indexing starts at zero, meaning the first character is at index 0, the second is at index 1, the third is at index 2, and so on. This is the same zero-based indexing that arrays use.
Accessing individual characters
Because a string is stored like an array, accessing an individual character works exactly the same way as accessing an element in an array. To retrieve a character at a specific index, write the name of the string followed by the index in square brackets.
The result of indexing into a string is always a single character. This operation takes constant time O(1) regardless of which index you use because the computer can calculate the exact memory address of any character directly from its index, just as it does with arrays.
You can also use the .at() member function, which performs bounds checking and throws an exception if the index is out of range:
Indexing from the end of a string
C++ does not have built-in negative indexing like Python. To access characters from the end of a string, you must calculate the index explicitly using the string’s length. The last character is at index s.length() - 1, the second-to-last is at s.length() - 2, and so on.
C++ also provides the .back() member function to access the last character directly:
While C++ does not offer Python’s negative indexing shorthand, writing s[s.length() - 1] is the standard idiom. It is genuinely useful in practice. Many string problems require ...