gpt4 book ai didi

c++ - 尝试替换字符串中的单词

转载 作者:太空狗 更新时间:2023-10-29 23:31:07 24 4
gpt4 key购买 nike

我试图从输出中获取单词并找到其中包含字母 Q 的任何单词。如果这个词是,则需要用“坏”一词代替。之后,我试图将每个单词附加到 output2。我在做这件事时遇到了麻烦。我编译时得到的错误是:

invalid conversion from 'const char*' to 'char' [-fpermissive]

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
string manipulate(string x);
int main(int argc, char* argv[])
{
string input, temp, output, output2, test, test2;
int b;
cout << "Enter a string: ";
getline(cin, input);
istringstream iss(input);
while (iss >> test)
{
if(test.length() != 3)
{
test.append(" ", 1);
output.append(test);
}
}

istringstream iss2(output);
while (iss2 >> test2)
{
for(int i = 0; i<test2.length(); i++)
{
switch(test2[i])
{
case 'q':
test2[1]="bad";
output2.append(test2);
break;
}

}
}
cout << "Your orginal string was: " << input << endl;
cout << "Your new string is: " << output2 << endl;
cin.get();
return 0;
}

最佳答案

有更简单的方法来做到这一点:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string s("Your homework is bad. Really bad.");

while (s.find("bad") != string::npos)
s.replace(s.find("bad"), 3, "good");

cout << s << endl;

return 0;
}

输出:

Your homework is good. Really good.

但是当指针是新值的子串时要注意大小写。在这种情况下,您可能希望移动索引以避免无限循环;示例:

string s("Your homework is good. Really good."),
needle("good"),
newVal("good to go");

size_t index = 0;

while ((index = s.find(needle, index)) != string::npos) {
s.replace(index, needle.length(), newVal);
index += newVal.length();
}

cout << s << endl;

输出

Your homework is good to go. Really good to go.

关于c++ - 尝试替换字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9053687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com