试图替换字符串中的单词

Trying to replace words in a string

本文关键字:单词 字符串 替换      更新时间:2023-10-16

我正在尝试从输出中提取单词,并找到其中包含字母Q的任何单词。如果该单词包含字母Q,则需要用单词"bad"替换它。之后,我尝试将每个单词附加到output2。我做这件事有困难。我编译时得到的错误是:

从"const char*"到"char"的转换无效[-fpermission]

#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.

这是编译错误的原因:

test2[1]="bad";

test2[1]属于char类型,"bad"属于const char*类型:此分配不合法。

使用std::string::replace()q更改为"bad":

test2.replace(i, 1, "bad");

由于您只需要替换第一次出现的'q'(我认为这是基于for循环中的逻辑),因此可以将for循环替换为:

size_t q_idx = test2.find('q');
if (std::string::npos != q_idx)
{
    test2.replace(q_idx, 1, "bad");
    output2.append(test2);
}

编辑:

替换整个单词:

test2 = "bad";

注意,如果output2包含具有当前逻辑的'q',则它们将包含字。这将是纠正它的一种方法:

output2.append(std::string::npos != test2.find('q') ? "bad" : test2);