如何在C ++中从输入中查找和替换字符串中的另一个字符串?

问题描述 投票:2回答:1

所以我想从我的字符串(str)中找到一个单词“ha”,并用另一个字符串(str2)替换为“wk”,如下所示:

    #include <iostream>
    #include <conio.h>
    #include <string>
    using namespace std;

int main ()
{
    string str;
    cin>>str;
    string str2("ha");
    while (str.find(str2) != std::string::npos) {
    str.replace(str.find(str2),str2.length(),"wk");
    cout << str << endl;
        }

    return 0;
}

但问题是,当我用另一个单词“lol haha​​”启动var1时,我无法使其工作。 not working when not haha at first [1]

谢谢 :)

c++ str-replace
1个回答
2
投票

operator>>std::string只读到它找到空白字符。你可能想要std::getline代替:

getline( std::cin, str );
© www.soinside.com 2019 - 2024. All rights reserved.