计算一个字符串在一个字符串中出现的次数

Counting the number of occurrences of a string within a string

本文关键字:一个 字符串 计算      更新时间:2023-10-16

计算字符串中所有子字符串的出现次数的最佳方法是什么?

示例:计算FooBarFooBarFooFoo的出现次数

方法之一是使用std::string find函数:

#include <string>
#include <iostream>
int main()
{
   int occurrences = 0;
   std::string::size_type pos = 0;
   std::string s = "FooBarFooBarFoo";
   std::string target = "Foo";
   while ((pos = s.find(target, pos )) != std::string::npos) {
          ++ occurrences;
          pos += target.length();
   }
   std::cout << occurrences << std::endl;
}
#include <iostream>
#include <string>
// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos;
     offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}
int main()
{
    std::cout << countSubstring("FooBarFooBarFoo", "Foo")    << 'n';
    return 0;
}

您应该使用KMP算法。它在O(M+N)时间内解决它,其中M和N是两个字符串的长度。更多信息-https://www.geeksforgeeks.org/frequency-substring-string/

所以KMP算法做的是,它搜索字符串模式。当一个模式的子模式在子模式中出现多个时,它使用该属性来提高时间复杂度,在最坏的情况下也是如此。

KMP的时间复杂度为O(n)。查看详细算法:https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/

#include <iostream>
#include<string>
using namespace std;
int frequency_Substr(string str,string substr)
{
    int count=0;
    for (int i = 0; i <str.size()-1; i++)
    {
        int m = 0;
        int n = i;
        for (int j = 0; j < substr.size(); j++)
        {
            if (str[n] == substr[j])
            {
                m++;
            }
            n++;
        }
        if (m == substr.size())
        {
            count++;
        }
    
    }
    cout << "total number of time substring occur in string is " << count << endl;
    return count;
}
int main()
{
    string x, y;
    cout << "enter string" << endl;
    cin >> x;
    cout << "enter substring" << endl;
    cin >> y;
    frequency_Substr(x, y);
    return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s1,s2;
    int i=0;
    cout<<"enter the string"<<endl;
    getline(cin,s1);
    cout<<"enter the substring"<<endl;
    cin>>s2;
    int count=0;
    string::iterator it=s1.begin();
    while(it!=s1.end())
    {
        if(*it==s2[0])
        {
            int x =s1.find(s2);
            string subs=s1.substr(x,s2.size());
            if(s2==subs)
                count++;
        }
        ++it;
    
    }
    cout<<count<<endl;
    return 0;
}
相关文章: