Manipulating std::string Objects

Iterate over String

How can I iterate through each character of a std::string using a range-based for loop?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved