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

How to find number of occurence and position of a substring in a string in C++

本文关键字:字符串 位置 c++      更新时间:2023-10-16

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

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 foundn";
                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:- ENDn";
        cin >> running;
        if(running == "END")
        {break;}
        else
        {
            Search(running, index);
        }
    }
    myReadFile.close();
    return 0;
}

查看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;

我终于做到了。我对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 foundn";
                found = false;
            }
        }
        n = 0;
    }
}