如何在C ++中查找字符串中子字符串的出现次数和位置

时间:2013-04-10 12:25:26

标签: c++ string

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

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

2 个答案:

答案 0 :(得分:2)

查看std::string::find reference。 Find有第二个参数,即搜索开始的位置。所以,只需将find放在一个循环中,将前一个find的结果作为第二个参数,直到find返回std :: string :: npos。有点像:

int startpos = 0;
int finds = 0;
while ((startpos = yourstring.find(substring, startpos)) != std::string::npos)
  ++finds;

答案 1 :(得分: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;
    }

}