使用迭代器插入到字符串的特定部分? (C++)

问题描述:

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

可以说我想在“one”后面加上:“two”。 空间会是str [3]是否正确?所以:在这种情况下,n = 3;使用迭代器插入到字符串的特定部分? (C++)

for (it=str.begin(); it < str.end(); it++,i++) 
{ 
    if(i == n) 
    {     
    // insert string add at current position   
    break; 
    } // if at correct position 
} // for 

*它允许我访问str [3]中的字符,但我不知道如何从那里添加字符串。任何帮助表示赞赏,谢谢。如果有任何混淆或不清楚请让我知道

+0

这似乎与http://stackoverflow.com/questions/2395275/how-to-navigate-through-a-vector-using-iterators-c和相当可疑片代码在你接受的答案中(你不会真的用这么复杂的方式来到第n个迭代器)。 – UncleBens 2010-03-07 11:24:01

您可以使用字符串类的insert方法。

string str = "one three"; 
string add = "two "; 
str.insert(4,add); // str is now "one two three" 

使用std::string::insert。要么是

str.insert(n, add); 

,或者使用下面的更宽泛的版本,它适用于任何容器(不仅std::string)。

str.insert(str.begin() + n, add.begin(), add.end()); 

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

其实你会希望4.'insert'在迭代器给出的项之前插入,而不是之后。 (您想要在空格之后插入,即在空格之后的下一个字符之前插入。) – UncleBens 2010-03-07 11:27:14