2
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

kevin
  • 1,834
  • 3
  • 18
  • 23
  • This seems to be related to http://stackoverflow.com/questions/2395275/how-to-navigate-through-a-vector-using-iterators-c and the rather questionable piece of code in your accepted answer (you won't really ever use such a convoluted way to get to the nth iterator). – UncleBens Mar 07 '10 at 11:24

3 Answers3

2

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
  • 32,009
  • 9
  • 68
  • 103
1

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
  • 445,704
  • 82
  • 492
  • 529
1
string::iterator it = str.begin() + 4;
str.insert(it, add.begin(), add.end());
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
  • 1
    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 Mar 07 '10 at 11:27