【问题标题】:Why doesn't the length of the string go beyond 16 characters when using .replace operator?为什么使用 .replace 运算符时字符串的长度不超过 16 个字符?
【发布时间】:2019-11-17 09:11:12
【问题描述】:

我正在尝试替换字符 '.'在我的带有“[.]”的字符串中,使用 .replace 函数,如下面的代码所示。但是,该字符串不超过 16 个字符。另一方面,通过使用 .insert 函数,字符串的长度没有限制。这种行为有什么解释吗?谢谢

我改用 .insert 函数。

newString = "255.100.50.0";
int len = newString.length(), i =0;
while(i < len){if(newString[i] == '.'){
    newString.replace(i,1, "[.]");
    len = newString.length();
    }
    i += 3;
}
cout << newString << endl;

【问题讨论】:

标签: c++ string c++11 stdstring


【解决方案1】:

无论当前字符是否为句点,都将i 增加 3。您只会查看每三个位置,而只是跳过并错过一些周期,这些周期恰好位于不能被 3 整除的位置。

【讨论】:

  • 这是真的!我不必在其他方法中增加 i,这就是为什么不会发生此问题的原因。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 2011-07-11
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多