计算一个字符串在一个字符串中出现的次数
Counting the number of occurrences of a string within a string
计算字符串中所有子字符串的出现次数的最佳方法是什么?
示例:计算FooBarFooBarFoo
中Foo
的出现次数
方法之一是使用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;
}
相关文章:
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何检查一个c++字符串中有多少相同的字符/数字
- 获取用C/C++打印的最后一个字符串
- cin >> int 给定一个字符串将 int 赋值为 0
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- C++为 void 指针分配一个字符串
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何在另一个字符串的x位置插入一个字符串?
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 在另一个字符串中插入文件扩展名之前的字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- C++自定义流操纵器,用于更改流上的下一个字符串
- 从类返回一个字符串 — 奇怪的行为
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 你能从"volatile const char*"构造一个字符串吗?(不使用`const_cast`