Inserting into a specific part of a string using iterators? (C++)
string str = "one three";
string::iterator it;
string add = "two ";
Lets say I want to add: "two " right after the s开发者_开发知识库pace in "one". the space would be str[3] correct? so: in this case, n = 3;
for (it=str.begin(); it < str.end(); it++,i++)
{
if(i == n)
{
// insert string add at current position
break;
} // if at correct position
} // for
*it would allow me to access the character at str[3], but I don't know how I would add in the string from there. Any help is appreciated, thanks. If anything is confusing or unclear please let me know
Use std::string::insert
. Either do
str.insert(n, add);
or use the following more generic version, which works for any container (not only std::string
).
str.insert(str.begin() + n, add.begin(), add.end());
You can make use of the insert
method of the string class.
string str = "one three";
string add = "two ";
str.insert(4,add); // str is now "one two three"
string::iterator it = str.begin() + 4;
str.insert(it, add.begin(), add.end());
精彩评论