Inserting
Inserting characters into an existing string can be done via the insert() function.
|
string& string::insert (size_type index, const string& str) string& string::insert (size_type index, const char* str)
Sample code:
string sString("aaaa");
cout << sString << endl;
sString.insert(2, string("bbbb"));
cout << sString << endl;
sString.insert(4, "cccc");
cout << sString << endl;
Output: aaaa aabbbbaa aabbccccbbaa |
Here’s a crazy version of insert() that allows you to insert a substring into a string at an arbitrary index:
string& string::insert (size_type index, const string& str, size_type startindex, size_type num)
Sample code:
string sString("aaaa");
const string sInsert("01234567");
sString.insert(2, sInsert, 3, 4); // insert substring of sInsert from index [3,7) into sString at index 2
cout << sString << endl;
Output: aa3456aa |
There is a flavor of insert() that inserts the first portion of a C-style string:
string& string::insert(size_type index, const char* str, size_type len)
Sample code:
string sString("aaaa");
sString.insert(2, "bcdef", 3);
cout << sString << endl;
Output: aabcdaa |
There’s also a flavor of insert() that inserts the same character multiple times:
string& string::insert(size_type index, size_type num, char c)
Sample code:
string sString("aaaa");
sString.insert(2, 4, 'c');
cout << sString << endl;
Output: aaccccaa |
And finally, the insert() function also has three different versions that use iterators:
|
void insert(iterator it, size_type num, char c) iterator string::insert(iterator it, char c) void string::insert(iterator it, InputIterator begin, InputIterator end)
|
A.1 — Static and dynamic libraries
|
Index
|
17.6 — std::string appending
|
A.1 — Static and dynamic libraries
Index
17.6 — std::string appending
[...] 17.7 — std::string inserting [...]
Glad to see you back! These tuts are much appreciated by many people!
“I’m baaaaaaaaack.”
Hi Alex,
I am glad that you are getting some time to write these tutorials.
These are the best I have seen so far, and perhaps better than some of the course books and textbooks. Please continue this excellent work and I hope people can help and contribute as much as they can for all your hard work.
I am eagerly waiting for tutorials on STL, e.g vectors, allocators, and other advanced topics. Your tutorials are very simple to understand and comprehend. The examples you give are great.
Thanks again for all your work. I am sure, all the newbies like us will be always thankful to you for teaching us C++. Thanks a lot. May God bless you!
The HTML symbol codes seems to be “broken” in the code examples.
HTML codes broken. Example of what I see.
string sString("aaaa");
cout << sString << endl;
:-) got replaced correctly
I love your tutorials Man. They are so beautiful. Best tutorials i could find on web. Thank you very much :)