From: Rusty Russell Date: Fri, 7 Jan 2011 23:47:37 +0000 (+1030) Subject: str: strcount X-Git-Url: http://git.ozlabs.org/?p=ccan;a=commitdiff_plain;h=053f9398c5959d070b7092653ec8f222200ab463;hp=d4929b8d2c8fc18ab16d2ef2bf7af11e87dac36d str: strcount Useful routine to count number of matches in a string. --- diff --git a/ccan/str/str.c b/ccan/str/str.c new file mode 100644 index 00000000..fa9809fb --- /dev/null +++ b/ccan/str/str.c @@ -0,0 +1,12 @@ +#include + +size_t strcount(const char *haystack, const char *needle) +{ + size_t i = 0, nlen = strlen(needle); + + while ((haystack = strstr(haystack, needle)) != NULL) { + i++; + haystack += nlen; + } + return i; +} diff --git a/ccan/str/str.h b/ccan/str/str.h index 8cfd7f29..770a40fd 100644 --- a/ccan/str/str.h +++ b/ccan/str/str.h @@ -55,4 +55,16 @@ static inline bool strends(const char *str, const char *postfix) #define stringify(expr) stringify_1(expr) /* Double-indirection required to stringify expansions */ #define stringify_1(expr) #expr + +/** + * strcount - Count number of (non-overlapping) occurrences of a substring. + * @haystack: a C string + * @needle: a substring + * + * Example: + * #define PRINT_COND_IF_FALSE(cond) \ + * ((cond) || printf("%s is false!", stringify(cond))) + */ +size_t strcount(const char *haystack, const char *needle); + #endif /* CCAN_STR_H */ diff --git a/ccan/str/test/run.c b/ccan/str/test/run.c index 4648692b..3ccadbe5 100644 --- a/ccan/str/test/run.c +++ b/ccan/str/test/run.c @@ -1,9 +1,9 @@ #include +#include #include #include #include -/* FIXME: ccanize */ #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) static char *substrings[] = { "far", "bar", "baz", "b", "ba", "z", "ar", NULL }; @@ -35,7 +35,7 @@ int main(int argc, char *argv[]) } } - plan_tests(n * n * 5 + 3); + plan_tests(n * n * 5 + 16); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { unsigned int k, identical = 0; @@ -87,5 +87,19 @@ int main(int argc, char *argv[]) "(sizeof(substrings) / sizeof(substrings[0]))")); ok1(streq(stringify(i == 0), "i == 0")); + ok1(strcount("aaaaaa", "b") == 0); + ok1(strcount("aaaaaa", "a") == 6); + ok1(strcount("aaaaaa", "aa") == 3); + ok1(strcount("aaaaaa", "aaa") == 2); + ok1(strcount("aaaaaa", "aaaa") == 1); + ok1(strcount("aaaaaa", "aaaaa") == 1); + ok1(strcount("aaaaaa", "aaaaaa") == 1); + ok1(strcount("aaa aaa", "b") == 0); + ok1(strcount("aaa aaa", "a") == 6); + ok1(strcount("aaa aaa", "aa") == 2); + ok1(strcount("aaa aaa", "aaa") == 2); + ok1(strcount("aaa aaa", "aaaa") == 0); + ok1(strcount("aaa aaa", "aaaaa") == 0); + return exit_status(); } diff --git a/tools/ccanlint/Makefile b/tools/ccanlint/Makefile index 854564aa..043c3fd2 100644 --- a/tools/ccanlint/Makefile +++ b/tools/ccanlint/Makefile @@ -9,6 +9,7 @@ CORE_OBJS := tools/ccanlint/ccanlint.o \ tools/tools.o \ tools/compile.o \ ccan/str_talloc/str_talloc.o ccan/grab_file/grab_file.o \ + ccan/str/str.o \ ccan/asort/asort.o \ ccan/btree/btree.o \ ccan/talloc/talloc.o ccan/noerr/noerr.o \