尝试替换字符串中的单词 [英] Trying to replace words in a string
问题描述
我正在尝试从输出中提取单词,并在其中找到带有字母Q的任何单词.如果有,请用坏"一词代替.之后,我尝试将每个单词附加到output2.我在执行此操作时遇到了麻烦.编译时出现的错误是:
I am trying to take the words from output and find any word with the letter Q in it. If the word does, it needs to be replaced by the word "bad". After that, I am trying to append each word to output2. I am having trouble doing this. The error I get when I compile is:
从'const char *'到'char'的无效转换[-fpermissive]
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;
}
推荐答案
有更简单的方法来做到这一点:
There is much easier way how to do that:
#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.
但是请注意当针是新值的子字符串时的情况.在这种情况下,您可能需要转移索引以避免无限循环;例如:
But watch out for case when the needle is a substring of the new value. In that case you might want to be shifting the index to avoid an infinite loop; example:
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.
这篇关于尝试替换字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!