C++查找/替换字符串

C++ Find/Replace Strings

本文关键字:字符串 替换 查找 C++      更新时间:2023-10-16

提前感谢您的任何帮助,如果这是一个双重帖子,我深表歉意,但我阅读了其他几个问题,但没有找到我想要的答案。

正在处理一个项目,我必须输入一个字符串(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);