c++ - 给定一个字符串,每当你看到单词 "ant"时,将单词 "termite"替换为字符串

标签 c++ string for-loop substring

我试图在不使用替换功能的情况下将打击文本中的所有“ Ant ”词替换为“白蚁”。我只能替换文本中的第一个单词。有人可以告诉我我在循环中做错了什么吗?谢谢你! 附言这也是学校的作业。我必须按照教授的要求以某种方式对其进行编码。

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

 void HomeworkHeader();

 string Text = "Auntie saw an ant cross the kitchen counter. Then latter she 
 saw a group of ants cross the floor. But, she was focused on adding a new 2 
 meter antenna to her 40 foot antenna mast. Friends would be coming over to 
 help with the raising and lowering of the antenna mast.";

 string FindAndSubstitutes(string bText, string OldWord, string NewWord);

 int main()
 {
      HomeworkHeader();
      cout << Text << endl;
      cout << endl;
      string Revise = FindAndSubstitutes(Text, "ant", "termite");
      cout << Revise;
      return 0;
  }

  string FindAndSubstitutes(string bText, string OldWord, string 
     NewWord)
  {
   int len = Text.length();
    int OldStrLen = OldWord.length();

    for (int i = 0; i < len; i++)
    {
        int WhereIsAnt = Text.find(OldWord);
        string partBefore = Text.substr(0, WhereIsAnt);
        string partAfter = Text.substr( WhereIsAnt + OldStrLen + 1);
        bText = partBefore + NewWord + partAfter;

     }

     return bText;
     }

最佳答案

您需要循环直到找不到任何 OldWord 并继续复制子字符串以替换为 NewWord,就像您已经做的那样。干杯,希望它有所帮助。

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

void HomeworkHeader();

string Text = "Auntie saw an ant cross the kitchen counter. Then latter she \
saw a group of ants cross the floor. But, she was focused on adding a new 2 \
meter antenna to her 40 foot antenna mast. Friends would be coming over to \
help with the raising and lowering of the antenna mast.";

string FindAndSubstitutes(string bText, string OldWord, string NewWord);

int main()
{
    HomeworkHeader();
    cout << Text << endl;
    cout << endl;
    string Revise = FindAndSubstitutes(Text, "ant", "termite");
    cout << Revise;
    return 0;
}

string FindAndSubstitutes(string Text, string OldWord, string NewWord)
{
    int len = Text.length();
    int OldStrLen = OldWord.length();
    int WhereIsAnt;

    while( (WhereIsAnt = Text.find(OldWord)) >= 0 )
    {
        string partBefore = Text.substr(0, WhereIsAnt);
        string partAfter = Text.substr( WhereIsAnt + OldStrLen);
        Text = partBefore + NewWord + partAfter;
    }

    return Text;
}

关于c++ - 给定一个字符串,每当你看到单词 "ant"时,将单词 "termite"替换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431974/

相关文章:

C++ 模板,分配给 "static"和 "dynamic"的对象有问题

java - 无法理解Core java for循环和switch case语句逻辑

Java 显式迭代器有效。隐式 forloop 产生 "Can only iterate over an array or an instance of java.lang.Iterable"

c - C 代码中的意外输出

c++ - 选择性迭代器

c++ - C++服务的自动延迟启动

c++ - 优先队列的push和pop和max_heap的插入和删除的时间复杂度是一样的吗?

javascript - 从字符串中删除空格、连字符和括号

python - 由于德语变音,Python 中的字符串不相等

java - 正则表达式 - 使用正则表达式在另一个字符串中搜索特定字符串