我正在努力查找一個字符串中子字符串的位置數。 以下代碼僅爲我提供了字符串中子字符串的起始位置。 請幫幫我。如何在C++中查找字符串中的子字符串的發生次數和位置
void Search(std::string SubString, vector<string> index)
{
vector<string>::const_iterator cii;
string temp;
bool found = false;
unsigned find = 0;
for(cii = index.begin(); cii != index.end(); cii++)
{
temp = *cii;
find = temp.find(SubString);
if(find != std::string::npos)//running.find()
{
cout << find << endl;
cout << *cii << endl;
found = true;
}
else
{
if((cii == index.end()) && found)
{
cout << "Not found\n";
found = false;
}
}
}
}
int main()
{
vector<string> index;
ifstream myReadFile;
string str, running;
myReadFile.open("example.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
while(std::getline(myReadFile, str))
{
index.push_back(str);
}
}
}
while(running != "END")
{
cout << "To Quit type:- END\n";
cin >> running;
if(running == "END")
{break;}
else
{
Search(running, index);
}
}
myReadFile.close();
return 0;
}
: - 感謝您的解決方案。我做的。請找到我更新的答案。 – 2013-04-10 13:08:33
你需要在每次迭代時增加startpos,否則它會繼續爲startpos返回相同的輸出。 – Ajit 2014-06-04 14:00:23