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

时间:2014-04-12 20:13:15

标签: c++ string algorithm substring infix-notation

我需要找出例如 test 出现在 ttest 中的次数,并且答案为2,或者例如 world w1o1r1l1d 中,答案就是一个。我已经编写了一个找到所有可能性的代码,然后检查它是否是我正在搜索的字符串,但这太慢了。

1 个答案:

答案 0 :(得分: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;
}