[ create a new paste ] login | about

Link: http://codepad.org/Jktgdbp7    [ raw code | output | fork ]

C, pasted on Apr 12:
#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;
}


Output:
1
2
3
4
5
6
[a] exists 0 times in []
[] exists 0 times in [a]
[a] exists 5 times in [abracadabra]
[br] exists 3 times in [abracadabra]
[test] exists 2 times in [ttest]
[world] exists 1 times in [w1o1r1l1d]


Create a new paste based on this one


Comments: