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

How to calculate how many times a string appears in another string?

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

例如,我需要找出testttest中出现了多少次,答案是2,或者例如w1o1r1d1dworld,答案是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;
}
相关文章: