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

1
  • This seems to be related to stackoverflow.com/questions/2395275/… 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). Commented Mar 7, 2010 at 11:24

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

1
string::iterator it = str.begin() + 4;
str.insert(it, add.begin(), add.end());

1 Comment

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.