2013/05/21

[C++]字串關鍵字搜尋範例


#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    string Data = "";
    string KeyWord = "";
    int Counter = 0;
    int Index = 0;

    cout << "Please input message: ";
    getline(cin,Data);
    cout << "Please input keyword: ";
    getline(cin,KeyWord);

    while(Index < Data.length())
    {
        if(Data.find(KeyWord,Index) != std::string::npos)
        {
            cout << "Find " << "\"" << KeyWord << "\"" << " at [" << Data.find(KeyWord,Index)  << "]."<< endl;
            Counter++;
            Index = Data.find(KeyWord,Index)+KeyWord.length() ;
        }

        else
        {
            break;
        }
    }

    cout << "\"" << KeyWord << "\"" <<  " appears "  << Counter << " times." << endl;

    system(("PAUSE"));
    return 0;
}