2

我正在努力寻找一个子串在一个stings中的位置数。下面的代码只为我提供了字符串中子字符串的起始位置。请帮我。

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;
}
4

2 回答 2

2

看看std::string::find 参考。Find 有第二个参数,即搜索开始的位置。因此,只需将 find 放入循环中,将前一个 find 的结果作为第二个参数,直到 find 返回 std::string::npos。类似于以下内容:

int startpos = 0;
int finds = 0;
while ((startpos = yourstring.find(substring, startpos)) != std::string::npos)
  ++finds;
于 2013-04-10T12:42:20.120 回答
0

最后我做到了。我对我的Search()功能做了一些小改动。找到下面的代码。

void Search(std::string SubString, vector<string> index)
{
    vector<string>::const_iterator cii;
    string temp;
    bool found = false;
    unsigned find = 0;
    static int n = 0;
    for(cii = index.begin(); cii != index.end(); cii++)
    {
        temp = *cii;
        std::string ::size_type pos = 0;
        while( (pos = temp.find( SubString, pos )) 
                 != std::string::npos ) 
        {
            n++;
            pos += SubString.size();
            cout << pos << " ";
        }
        if(n)
        {
        cout << " \n ";
        cout << *cii << endl;
        found = true;
        }
        else
        {
            if((cii == index.end() - 1) && !found)
            {
                cout << "Not found\n";
                found = false;
            }
        }
        n = 0;
    }

}
于 2013-04-10T13:08:01.317 回答