如何计算一个字符串在另一个字符串中出现的次数
How to calculate how many times a string appears in another string?
例如,我需要找出test在ttest中出现了多少次,答案是2,或者例如w1o1r1d1d的world,答案是1。我已经写了一个代码,它可以找到所有的可能性,然后检查它是否是我正在搜索的字符串,但速度太慢了。
我会尝试递归解决方案。
一个字母字符串在另一个字符串中出现的次数就是字符在其中出现的次数。
the number of time "r" appears in "program" is 2
n字母字符串出现在另一个字符串中的次数为:
(n-1)-字符串在第一个字母的第一次匹配后出现的次数加上n字母字符串在第一次匹配之后出现的次数
the number of times "test" appears in "ttest" is
the number of times "est" appears in "test"
+ the number of times "test" appears in "test"
#include <stdio.h>
#include <string.h>
int count(const char *needle, const char *stack) {
int n = 0;
const char *p;
if (*stack == 0) return 0;
if (*needle == 0) return 0;
p = strchr(stack, *needle);
if (needle[1] == 0) n += !!p;
if (p) {
n += count(needle + 1, p + 1);
n += count(needle, p + 1);
}
return n;
}
int main(void) {
const char *needle, *stack;
needle = "a"; stack = "";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
needle = ""; stack = "a";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
needle = "a"; stack = "abracadabra";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
needle = "br"; stack = "abracadabra";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
needle = "test"; stack = "ttest";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
needle = "world"; stack = "w1o1r1l1d";
printf("[%s] exists %d times in [%s]n", needle, count(needle, stack), stack);
return 0;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串