如何在c++中查找字符串中出现的字符串

How to find occurrences of a string in string in C++?

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

如何在c++中找到字符串的出现?

场景如下。

string base_string = "BF;1;2;3;FF;10;20;30;BF;11;;22;33;FF;100;200;300;BF;110;;220;330;FF;1000;2000;3000";
string to_find_occurances_of = "BF";
int occurrences = 0;
string::size_type start = 0;
while ((start = base_string.find(to_find_occurrences_of, start)) != string::npos) {
    ++occurrences;
    start += to_find_occurrences_of.length(); // see the note
}

string::find接受要在调用对象中查找的字符串和(在此重载中)开始查找的字符位置,并返回字符串出现的位置,如果没有找到字符串,则返回string::npos

变量start从0(第一个字符)开始,在循环的条件下,您使用start告诉find从哪里开始查找,然后将find的返回值赋给start。增加发生次数;现在start保持了字符串的位置,您可以跳过to_find_occurrences_of.length() 1字符并重新开始查找。


1 drhirsch指出,如果to_find_occurrences_of包含重复的字符序列,执行start += to_find_occurrences_of.length()可能会跳过一些出现的字符。例如,如果base_string"ffff", to_find_occurrences_of"ff",那么如果将to_find_occurrences_of.length()添加到start,则只会计数2次。如果您想避免这种情况,请将1而不是to_find_occurrences_of.length()添加到start中,在该示例中,将计数出现3次而不是2次。

下面是使用用户定义的查找函数在字符串中查找字符串的代码

int Find(char OrgStr[], char szFind[]);
void main(){
   int iCount = Find("babbabaab ab", "ab");
   //cout<<"No of 'abe' : " << iCount <<endl;
}
int Find(char orgStr[], char findStr[]){    
    int i,j,k,l,szLen,orgLen;
    char temp[] = " ";
    orgLen = strlen(orgStr);
    szLen = strlen(findStr); 
    k= 0;
    i = 0;
    l = 0;
    while( l < orgLen )
    {
        i = (orgLen - ( orgLen - l));
        for( j = 0; j < szLen; j++)
        {
            temp[j] = orgStr[i];            
            i++;
        }
        temp[j] = '';
        if(strcmp(temp,findStr) == 0)
        {
            k++;
        }
        strcpy(temp,"");
        l++;
    }
    cout<<"No of 'ab' : " << k <<endl;
    return k;
    //strcpy(temp,"");
}    

在这种情况下可以使用Boost c++库。下面是一个字符串匹配的例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
#include <vector>
using StringRange = boost::iterator_range<std::string::const_iterator>;
int main()
{
    std::string base_string = "BF;1;2;3;FF;10;20;30;BF;11;;22;33;FF;100;200;300;BF;110;;220;330;FF;1000;2000;3000";
    std::string to_find_occurances_of = "BF";
    std::vector<StringRange> matches;
    boost::find_all(matches, base_string, to_find_occurances_of);
    for (auto match : matches) {
        std::cout << "Found [" << to_find_occurances_of << "] at index " << match.begin() - base_string.begin() << ".n";
    }
}

这段代码打印:

Found [BF] at index 0.
Found [BF] at index 21.
Found [BF] at index 49.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
      string str("BF;1;2;3;FF;10;20;30;BF;11;;22;33;FF;100;200;300;BF;110;;220;330;FF;1000;2000;3000");
      string str2 ("BF");
      size_t found;
      // different member versions of find in the same order as above:
      found=str.find(str2);
//print
            return 0;
}