コードには (少なくとも) 他に 2 つのものが必要です。1 つ目は文字列の文字列全体を処理するループand
で、2 つ目は既にチェック済みのものをスキップする機能です。
また、文字列がで始まる可能性に対処したい場合もありますが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
文字列の先頭にあることに偏執的であり、Michael は文字列の末尾(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)私が衒学者になるなら、ちゃんとやったほうがいいよ :-)