【问题标题】:Inserting into a specific part of a string using iterators? (C++)使用迭代器插入字符串的特定部分? (C++)
【发布时间】:2010-03-07 11:02:39
【问题描述】:
string str = "one three";
string::iterator it;
string add = "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] 处的字符,但我不知道如何从那里添加字符串。任何帮助表示赞赏,谢谢。如果有任何令人困惑或不清楚的地方,请告诉我

【问题讨论】:

  • 这似乎与stackoverflow.com/questions/2395275/… 以及您接受的答案中相当有问题的一段代码有关(您永远不会使用如此复杂的方式来获取第 n 个迭代器)。跨度>

标签: c++ iterator


【解决方案1】:

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

str.insert(n, add);

或使用以下更通用的版本,它适用于任何容器(不仅是std::string)。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:
      string::iterator it = str.begin() + 4;
      str.insert(it, add.begin(), add.end());
      

      【讨论】:

      • 实际上你想要 4。insert 在迭代器给出的项目之前插入,而不是之后。 (您想在空格之后插入,即在空格之后的下一个字符之前。)
      猜你喜欢
      • 2017-12-15
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2011-07-22
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      相关资源
      最近更新 更多