tags:

views:

55

answers:

3
string str = "one three";
string::iterator it;
string add = "two ";

Lets say I want to add: "two " right after the space 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

+1  A: 

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());
avakar
+1  A: 

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"
codaddict
+1  A: 
string::iterator it = str.begin() + 4;
str.insert(it, add.begin(), add.end());
AraK
Actually you'd want 4. `insert` inserts before the item given by iterator, not after. (You want to insert after the space, i.e before the next character after the space.)
UncleBens