Manipulating std::string Objects

Insert Substring in C++

How can I insert a substring into a specific position within a std::string?

Abstract art representing computer programming

Inserting a substring into a specific position within a std::string is done using the insert() method. This method modifies the original string by adding the new substring at the specified position.

Basic Usage

The insert() method requires two arguments: the position to insert the substring and the substring itself. For example:

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hello!"};
  Greeting.insert(5, " World");
  std::cout << Greeting;
}
Hello World!

Inserting a Character

You can also insert a single character at a specific position.

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hell World!"};
  Greeting.insert(4, "o");
  std::cout << Greeting;
}
Hello World!

Inserting Multiple Characters

The insert() method can also insert multiple characters at once.

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hello!"};
  Greeting.insert(5, "!!!", 2);
  std::cout << Greeting;
}
Hello!!!

Considerations

  • Position Index: Ensure the position index is within the bounds of the string to avoid undefined behavior.
  • Efficiency: Frequent insertions can lead to performance issues due to potential reallocations.

Advanced Usage

You can also insert a substring from another string by specifying the starting position and length.

#include <iostream>
#include <string>

int main(){
  std::string Greeting{"Hello "};
  std::string Name{"Alice Wonderland"};

  Greeting.insert(6, Name, 0, 5);
  std::cout << Greeting;
}
Hello Alice

In summary, the insert() method is versatile and allows you to add substrings, single characters, or multiple characters to a std::string at any position you need.

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