0
0
CppHow-ToBeginner · 3 min read

How to Iterate Over String in C++: Simple Examples and Tips

In C++, you can iterate over a string using a for loop with an index, a range-based for loop, or iterators. Each method lets you access each character in the string one by one.
📐

Syntax

Here are common ways to iterate over a std::string in C++:

  • Index-based loop: Use a for loop with an integer index to access characters by position.
  • Range-based for loop: Use C++11's range-based for loop to access each character directly.
  • Iterator loop: Use string iterators to traverse the string from beginning to end.
cpp
std::string s = "hello";

// Index-based loop
for (size_t i = 0; i < s.size(); ++i) {
    char c = s[i];
}

// Range-based for loop
for (char c : s) {
    // use c
}

// Iterator loop
for (auto it = s.begin(); it != s.end(); ++it) {
    char c = *it;
}
💻

Example

This example shows how to print each character of a string on its own line using a range-based for loop.

cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "Hello, C++!";
    for (char c : text) {
        std::cout << c << '\n';
    }
    return 0;
}
Output
H e l l o , C + + !
⚠️

Common Pitfalls

Common mistakes when iterating over strings include:

  • Using a signed integer for the index, which can cause issues if the string is very large.
  • Accessing characters beyond the string length, causing undefined behavior.
  • Modifying the string while iterating without care, which can invalidate iterators.

Always use size_t for indices and check bounds.

cpp
std::string s = "test";

// Wrong: using int and going past end
for (int i = 0; i <= s.size(); ++i) { // <= causes out-of-bounds
    char c = s[i]; // undefined behavior when i == s.size()
}

// Right:
for (size_t i = 0; i < s.size(); ++i) {
    char c = s[i];
}
📊

Quick Reference

Summary tips for iterating over strings in C++:

  • Use size_t for indices to avoid signed/unsigned issues.
  • Range-based for loops are simple and safe for read-only access.
  • Use iterators when you need more control or to modify the string.
  • Always ensure your loop conditions prevent out-of-bounds access.

Key Takeaways

Use range-based for loops for simple and safe string iteration in C++.
Always use size_t for indexing to avoid errors with string length.
Avoid accessing characters beyond the string's size to prevent crashes.
Iterators provide flexible ways to traverse and modify strings.
Check loop conditions carefully to keep iteration within string bounds.