我正在查看一些示例,但我似乎无法理解为什么字符串替换功能不起作用。我使用的是 Visual C++ 2010
我尝试编译的代码行是:
string MyClass::replacestr (const string &input){
string subString = "str";
string subString2 = "STR";
for(int index = input.find(subString); index != string::npos; index = input.find(subString, index +subString.length()))
{
input.replace(index, 2, subString2);
}
}
它在 Visual Studio 中给了我这个错误:
3 IntelliSense: no instance of overloaded function "std::basic_string<_Elem, _Traits, _Ax>::replace [with _Elem=char, _Traits=std::char_traits<char>, _Ax=std::allocator<char>]" matches the argument list and object (the object has type qualifiers that prevent a match) c:\..test.cpp 36 Test
我只是不明白为什么它不能按照 C++ 引用网站中解释的方式工作。
最佳答案
字符串替换更改字符串的内容。您的字符串被标记为 const。这意味着您无法对其调用替换。
关于C++ - string.replace 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392542/