string str = "one three";
string::iterator it;
string add = "two ";
假设我想在“one”中的空格后面添加“two”。 空格将是 str[3] 正确吗?所以:在这种情况下,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
*它将允许我访问 str[3] 处的字符,但我不知道如何从那里添加字符串。如有任何帮助,我们将不胜感激,谢谢。如果有任何令人困惑或不清楚的地方,请告诉我
最佳答案
使用std::string::insert
。要么做
str.insert(n, add);
或使用以下更通用的版本,它适用于任何容器(不仅是 std::string
)。
str.insert(str.begin() + n, add.begin(), add.end());
关于c++ - 使用迭代器插入字符串的特定部分? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2395999/