您的代码中需要(至少)另外两件事。第一个是为字符串处理整个字符串的循环,and
第二个是跳过已经检查过的字符串的能力。
您可能还想处理字符串可能以 开头的可能性and
,尽管这不太可能:对您期望的内容保持自由,对您交付的内容保持具体。
以下代码将是一个很好的起点:
#include <iostream>
#include <string>
int main (void) {
std::string inputStr = "one thousand and fifty one";
std::string killStr = "and ";
size_t startPos = 0;
size_t andPos;
while ((andPos = inputStr.find (killStr, startPos)) != std::string::npos) {
if ((andPos == 0) || (inputStr[(andPos - 1)] != 's')) {
inputStr.erase(andPos, killStr.length());
startPos = andPos;
} else {
startPos = andPos + 1;
}
}
std::cout << inputStr << '\n';
return 0;
}
而且,由于我and
对在字符串的开头有偏执,迈克尔正确地叫我不要在字符串的末尾处理它(a),你可以修改它这样做:
#include <iostream>
#include <string>
#include <cstring>
static bool endsWith (std::string s1, std::string s2) {
size_t s1Len = s1.length();
size_t s2Len = s2.length();
if (s2Len > s1Len)
return false;
return (strcmp (s1.c_str() + s1Len - s2Len, s2.c_str()) == 0);
}
int main (void) {
std::string inputStr = "and one thousand and fifty one thousand and";
std::string killStr = "and ";
size_t startPos = 0;
size_t andPos;
while ((andPos = inputStr.find (killStr, startPos)) != std::string::npos) {
if ((andPos == 0) || (inputStr[(andPos - 1)] != 's')) {
inputStr.erase (andPos, killStr.length());
startPos = andPos;
} else {
startPos = andPos + 1;
}
}
if (!endsWith (inputStr, "sand") && endsWith (inputStr, "and"))
inputStr.erase (inputStr.length() - 3);
std::cout << inputStr << '\n';
return 0;
}
(a)如果我要成为一个书呆子,我最好把它做好:-)