Manipulating std::string Objects

Replace Substring in C++

How can I replace a substring within a std::string with another string?

Abstract art representing computer programming

Replacing a substring within a std::string with another string is accomplished using the replace() method. This method allows you to specify the starting position, the number of characters to replace, and the new substring.

Basic Usage

The replace() method requires three arguments: the starting position, the number of characters to replace, and the new substring. For example:

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hello World!"};

  Greeting.replace(6, 5, "Everyone");

  std::cout << Greeting;
}
Hello Everyone!

Replacing with a Different Length

The new substring does not need to be the same length as the substring being replaced. The string will adjust its size accordingly.

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hello Everyone!"};

  Greeting.replace(6, 8, "World");

  std::cout << Greeting;
}
Hello World!

Using Iterators

You can also use iterators to specify the range of characters to replace. This can be useful when working with more complex string manipulations.

#include <iostream>
#include <string>

int main() {
  std::string Greeting{"Hello World!"};
  std::string Replacement{"Everyone"};

  Greeting.replace(Greeting.begin() + 6,   
                   Greeting.begin() + 11,  
                   Replacement);  

  std::cout << Greeting;
}
Hello Everyone!

Considerations

  • Bounds Checking: Ensure the starting position and length are within the bounds of the string to avoid undefined behavior.
  • Efficiency: Large replacements can be inefficient due to potential reallocations.

Advanced Usage

For more control, you can replace a substring from another string by specifying the starting position and length within the new string.

#include <iostream>
#include <string>

int main() {
  std::string Greeting{"Hello World!"};
  std::string Replacement{"Greetings Earthlings"};

  Greeting.replace(6, 5, Replacement, 10, 5);  

  std::cout << Greeting;
}
Hello Earth!

The replace() method is powerful and flexible, making it easy to modify parts of a std::string as needed.

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