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.
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
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
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
const
for read-only access and omit it for modifying characters.By using the range-based for loop, you can easily and efficiently iterate over each character in a std::string
.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory