C++查找/替换字符串
C++ Find/Replace Strings
提前感谢您的任何帮助,如果这是一个双重帖子,我深表歉意,但我阅读了其他几个问题,但没有找到我想要的答案。
我正在处理一个项目,我必须输入一个字符串(String1),然后在String1中找到一个特定的字符串(String2)。 然后我必须用一个新字符串(String3)替换String2。
希望这是有道理的。 无论如何,我能够达到预期的结果,但这是情境。 关于代码,我会在路上解释。
int main()
{
string string1, from, to, newString;
cout << "Enter string 1: ";
getline(cin, string1);
cout << "Enter string 2: ";
cin >> from;
cout << "Enter string 3: ";
cin >> to;
newString = replaceSubstring(string1, from, to);
cout << "n" << newString;
}
string replaceSubstring(string string1, string from, string to)
{
int index, n, x = 0;
n = from.length();
while (x < string1.length() - 1)
{
index = string1.find(from, x);
string1.replace(index, n, to);
x = index + to.length() - 1;
}
return string1;
}
我应该输入以下内容:"他在这个小镇上生活了很长时间。 他于1950年毕业。
然后我应该用"她"替换所有"他"的实例。
当我尝试这样做时,我收到以下错误:
在抛出"std::out_of_range"
实例后终止调用 what(): basic_string::替换
中止(核心转储)
但是,如果我输入类似的东西。
字符串 1 = "嘿嘿"
字符串 2 = "他"
字符串 3 = "她"
它将输出:
"她她"
当您的FIND
调用失败时,您将在此区域出现不正确的index
:
index = string1.find(string2, x);
string1.replace(index, n, string3);
在将index
的值传递到Replace
之前检查
首先,如果函数"就地"更改原始字符串会更好。在这种情况下,它看起来像一个泛型函数替换,类似于成员函数替换。
调用后应检查索引是否
index = string1.find(string2, x);
等于 std::string::npos
。否则,该函数将引发异常。
还有这个声明
x = index + to.length() - 1;
错了
它应该看起来像
x = index + to.length();
例如,假设您有值为 "a"
的字符串,并希望将其替换为 "ba"
。在这种情况下,如果使用您的语句,x 将等于 1 ( x = 0 + 2 - 1 )。并将指向"BA"中的"a"。并且该函数再次将"a"替换为"ba",您将获得"bba",依此类推。也就是说,循环将是无限的。
我会按以下方式编写函数
#include <iostream>
#include <string>
void replace_all( std::string &s1, const std::string &s2, const std::string &s3 )
{
for ( std::string::size_type pos = 0;
( pos = s1.find( s2, pos ) ) != std::string::npos;
pos += s3.size() )
{
s1.replace( pos, s2.size(), s3 );
}
}
int main()
{
std::string s1( "Hello world, world, world" );
std::string s2( "world" );
std::string s3( "mccdlibby" );
std::cout << s1 << std::endl;
replace_all( s1, s2, s3 );
std::cout << s1 << std::endl;
return 0;
}
输出为
Hello world, world, world
Hello mccdlibby, mccdlibby, mccdlibby
find 函数返回 string x
的起始索引,索引从 0 to len-1
开始,而不是1 to len
。
int idx = string1.find(string2, x);
if(idx >= 0)
string1.replace(index, n, string3);
- 如何使用regex_replace将子字符串替换为字符串中的另一个子字符串,同时保持整个文本完整?
- 使用C++将一个字符串替换为另一个字符串
- 简单的字符串替换给出错误,尽管参数正确
- UnicodeString 将一个子字符串替换为另一个子字符串
- C++字符串.替换生成"No matching function for call"错误
- std::字符串替换不保留结尾?
- GCC Bug,使用尖括号通过宏包含标头时"linux"路径中的字符串"<>"替换为 "1"
- 字符串替换问题
- 将带双引号的字符串替换为带双引号的字符串
- 如何在C++中将字符串替换为"Match case"和"Match whole word"
- 字符串替换和奇怪的字符
- C++中的字符串反转不将旧字符串替换为新字符串
- 用c++字符串替换snprintf
- 字符串::替换在有效的迭代器上抛出 std::out_of_range
- 简单的标准::字符串替换在C++
- C++字符串替换函数无限循环
- 分析字符串替换内存泄漏
- C++:-用另一个字符串替换一段字符串
- 提升字符串替换不会用字符串替换换行符
- C++中任意长度字符串的字符串替换