Iterate over String
How can I iterate through each character of a std::string
using a range-based for loop?
Iterating through each character of a std::string
using a range-based for loop is a convenient and efficient way to access and manipulate each character individually.
Basic Usage
The range-based for loop in C++ simplifies the process of iterating through the elements of a container like std::string
. Here's how you can do it:
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello"};
for (const char& Character : Greeting) {
std::cout << Character << '\n';
}
}
H
e
l
l
o
Modifying Characters
If you need to modify the characters in the string, you can omit the const
keyword and use a reference.
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello"};
for (char& Character : Greeting) {
Character = toupper(Character);
}
std::cout << Greeting;
}
HELLO
Accessing Index
If you need the index of each character, use a traditional for loop with the at()
method or direct indexing.
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello"};
for (size_t i = 0; i < Greeting.size(); ++i) {
std::cout << "Character at index "
<< i << " is " << Greeting[i] << '\n';
}
}
Character at index 0 is H
Character at index 1 is e
Character at index 2 is l
Character at index 3 is l
Character at index 4 is o
Considerations
- Read-Only vs Modifiable: Use
const
for read-only access and omit it for modifying characters. - Performance: The range-based for loop is efficient and concise for most use cases.
By using the range-based for loop, you can easily and efficiently iterate over each character in a std::string
.
Manipulating std::string
Objects
A practical guide covering the most useful methods and operators for working with std::string
objects and their memory