【问题标题】:my (find & replace) method is not working properly我的(查找和替换)方法无法正常工作
【发布时间】:2021-11-24 11:10:01
【问题描述】:

我实际上正在尝试编写一个程序来对给定的字符串执行(查找和替换),但它不能正常工作(它在第一次出现时部分特别工作)。

有什么想法吗?下面是代码:

string Find_Replace(string str,string substr,string replacement){
    int x = substr.length();
    int i = 0;
    for(i = str.find(substr,0);i!=string::npos;i=str.find(substr,i)){
        str.replace(i,i+x,replacement);
        i++;
    }
    return str;
}
int main(){
cout << "Please enter a text:-" << endl;
    string str;
    string substr;
    string replacement;
    getline(cin, str);
    cout<<"Please enter a word to find:-"<<endl;
    getline(cin,substr);
    cout<<"Please enter the replacement text:-"<<endl;
    getline(cin,replacement);
    cout<<"The text after process:-"<<endl;
    cout<<Find_Replace(str,substr,replacement);
    return 0;
}

【问题讨论】:

  • 请问实际输出与预期输出?
  • @ErmiyaEskandary 如果我写了例如“我吃代码,你吃代码”并将“吃”替换为“爱”,那么预期将是“我爱代码,你爱代码”,但实际是“我爱你,你爱”
  • 字符串substr和replacement是否保证长度相同?如果没有,您可能需要在字符串中间插入/删除字符,而本程序不会这样做。

标签: c++ string replace find function-definition


【解决方案1】:

这个成员函数replace的调用

str.replace(i,i+x,replacement);

不正确。第二个参数必须指定要替换的字符数。

函数的定义方式如下

std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement )
{
    auto n1 = substr.length();
    auto n2 = replacement.size();

    for( auto pos = str.find( substr, 0 );
         pos != std::string::npos; 
         pos = str.find(substr, pos ) )
    {
        str.replace( pos, n1, replacement );
        pos += n2;
    }

    return str;
}

这是一个演示程序。

#include <iostream>
#include <string>

std::string & Find_Replace( std::string &str, const std::string &substr, const std::string &replacement )
{
    auto n1 = substr.length();
    auto n2 = replacement.size();

    for( auto pos = str.find( substr, 0 );
         pos != std::string::npos; 
         pos = str.find(substr, pos ) )
    {
        str.replace( pos, n1, replacement );
        pos += n2;
    }

    return str;
}

int main() 
{
    std::string s( "Hello World!" );
    
    std::cout << Find_Replace( s, "World", "C++ strings" ) << '\n';
    
    return 0;
}

程序输出是

Hello C++ strings!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多