我试图在不使用替换功能的情况下将打击文本中的所有“ 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/