如何从 C++ 输入中查找字符串并将其替换为另一个字符串?
How to find and replace string with another string from input in C++?
所以我想从我的字符串 (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]
谢谢你:)
operator>>
for std::string
only reads until it finds a whitespace character. You probably want std::getline
改为:
getline( std::cin, str );
所以我想从我的字符串 (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]
谢谢你:)
operator>>
for std::string
only reads until it finds a whitespace character. You probably want std::getline
改为:
getline( std::cin, str );