简体   繁体   English

C ++查找/替换字符串

[英]C++ Find/Replace Strings

thanks for any help in advance and apologies if this is a double post, but I read through a few other questions and I didn't find the answer I was looking for. 感谢您的事先帮助和歉意,如果这是重复的帖子,但是我通读了其他一些问题,但没有找到我想要的答案。

I am working on a project where I have to input a string (String1) and then find a specific string (String2) within String1. 我正在一个项目中,我必须输入一个字符串(String1),然后在String1中找到一个特定的字符串(String2)。 Then I have to replace String2 with a new string (String3). 然后,我必须用新的字符串(String3)替换String2。

Hope that makes sense. 希望有道理。 Anyways, I am able to achieve the desired result, but it is situational. 无论如何,我都能达到预期的效果,但这是视情况而定。 On to the code and I'll explain on the way. 在代码上,我将在后面解释。

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;
}

I am supposed to input the following: "He lived in this small town for a long time. He graduated in 1950." 我应该输入以下内容:“他在这个小镇上住了很长时间。他于1950年毕业。”

And then I am supposed to replace all instances of "He" with "She". 然后我应该用“她”替换所有“他”的实例。

When I attempt this I get the following error: 当我尝试这样做时,出现以下错误:

terminate called after throwing an instance of 'std::out_of_range' 抛出'std :: out_of_range'实例后调用终止
what(): basic_string::replace what():basic_string :: replace
Abort (core dumped) 中止(核心弃权)

However, if I enter something like. 但是,如果我输入类似的内容。

String1 = "He He" String1 =“何和”
String2 = "He" String2 =“他”
String3 = "She" String3 =“她”

It will output: 它将输出:

"She She" “她她”

When your FIND call fails, you will have an incorrect index at this area: 当您的FIND呼叫失败时,您将在此区域使用错误的index

   index = string1.find(string2, x);
   string1.replace(index, n, string3);

Check the value of index before passing it into Replace 在将index传递到Replace之前检查index的值

First of all it would be better if the function would change the original string "in place". 首先,如果函数将原始字符串更改为“ in place”会更好。 In this case it would look as a generic function replace similar to member function replace. 在这种情况下,它将看起来像泛型函数替换,类似于成员函数替换。

You shall check whether index after call 通话后请检查是否索引

index = string1.find(string2, x);

is equal to std::string::npos . 等于std::string::npos Otherwise the function will throw an exception. 否则,该函数将引发异常。

Also this statement 另外这句话

x = index + to.length() - 1;

is wrong 是错的

It should look like 它看起来像

x = index + to.length();

For example assume that you have string with value "a" and want to substitute it for "ba" . 例如,假设您具有值为"a"字符串,并希望将其替换为"ba" In this case if to use your statement x will be equal to 1 ( x = 0 + 2 - 1 ). 在这种情况下,如果使用您的语句,x将等于1(x = 0 + 2-1)。 and will point to "a" in "ba". 并指向“ ba”中的“ a”。 And the function again will replace "a" to "ba" and you will get "bba" and so on. 然后函数再次将“ a”替换为“ ba”,您将得到“ bba”,依此类推。 That is the loop will be infinite. 那就是循环将是无限的。

I would write the function the following way 我将通过以下方式编写函数

#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;
}

The output is 输出是

Hello world, world, world
Hello mccdlibby, mccdlibby, mccdlibby

Find function returns the starting index of string x and index start from 0 to len-1 instead of 1 to len . Find函数返回string x的起始索引,索引从0 to len-1而不是1 to len

int idx = string1.find(string2, x);
if(idx >= 0)
    string1.replace(index, n, string3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM