Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c++ - Trying to replace words in a string

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:

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

output:

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;

outputs

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...