【发布时间】:2018-06-19 20:06:20
【问题描述】:
努力寻找一种方法将“他”替换为“他或她”,将“他的”替换为“他或她的”,而不像我的代码如下所示将“the”替换为“the or she”:
#include <iostream>
#include <string>
using namespace std;
void myReplace(string& str, const string& oldStr, const string& newStr)
{
if (oldStr.empty())
{
return;
}
for (size_t pos = 0; (pos = str.find(oldStr, pos)) != string::npos;)
{
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
int main()
{
string searchStr;
Beginning:
cout << "Please enter a sentence (Maximum of 100 characters)\n"
<< "Or type 'exit' to close the program\n";
getline(cin, searchStr);
cout << "\nYour input:\n\t" << searchStr;
myReplace(searchStr, "he", "he or she");
cout << "\nReplaced Text\n\t" << searchStr << "\n\n";
goto Beginning;
}
我的程序做了什么...
Input: He is the man
Output: He or she is the or she man
应该怎么做……
Input: He is the man
Output: He or she is the man
任何人都可以帮助我解决这个问题。 如果您要问... 是的,我到处搜索谷歌。这该死的东西不符合我的需要。 提前感谢
【问题讨论】:
-
你不能像你一样使用简单的查找替换,你必须检查上下文以确保匹配整个单词。一个词和另一个词的区别是什么?哦,别忘了标点符号不应该算在“单词”中。
-
你想替换下面的“他”(带空格)-->“他或她”“他”(两个空格)-->“他或她”
-
你的程序永远不会因为那个讨厌的
goto语句而退出,并且它不能编译,缺少一些包含。 -
哦,从不使用
goto而不是循环。 -
@Someprogrammerdude 我缺乏英语肯定会害死我。正如您所指出的,对字符串进行标记并比较整个单词确实更好。
标签: c++ codeblocks