How to Insert into String in C++: Syntax and Examples
In C++, you can insert text into a string using the
insert() method, which allows you to specify the position and the text to add. For example, str.insert(pos, "text") inserts "text" at the index pos in the string str.Syntax
The insert() method in C++ strings lets you add characters or another string at a specific position.
str.insert(pos, s): Inserts stringsstarting at indexpos.pos: The zero-based index where insertion begins.s: The string or characters to insert.
cpp
string& insert (size_t pos, const string& str);
Example
This example shows how to insert a substring into a string at a specific position.
cpp
#include <iostream> #include <string> int main() { std::string str = "Hello World!"; str.insert(6, "Beautiful "); std::cout << str << std::endl; return 0; }
Output
Hello Beautiful World!
Common Pitfalls
Common mistakes when using insert() include:
- Using an invalid position (greater than string length), which causes an exception.
- Forgetting that string indices start at 0.
- Trying to insert into a const string (which is not allowed).
cpp
#include <iostream> #include <string> int main() { std::string str = "Hello"; // Wrong: position out of range // str.insert(10, "World"); // This will throw std::out_of_range // Correct usage: str.insert(5, " World"); std::cout << str << std::endl; return 0; }
Output
Hello World
Quick Reference
Remember these tips when inserting into strings:
- Positions start at 0.
- Position must be less than or equal to string length.
insert()modifies the original string.- You can insert single characters or whole strings.
Key Takeaways
Use
insert(pos, text) to add text at a specific position in a C++ string.Ensure the position is within the string length to avoid errors.
String indices start at zero, so count carefully.
insert() changes the original string directly.You can insert both single characters and strings using
insert().