Skip to content

Instantly share code, notes, and snippets.

@aktau
Created September 4, 2014 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aktau/458d8c09f80857f3ea94 to your computer and use it in GitHub Desktop.
Save aktau/458d8c09f80857f3ea94 to your computer and use it in GitHub Desktop.
cntchr function
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
size_t cntchr(const char *str, char value) {
size_t count = 0;
while ((str = strchr(str, value)) != NULL) {
++str;
++count;
}
return count;
}
size_t cntnchr(const char *str, char value, size_t num) {
size_t count = 0;
const char *pos;
while ((pos = memchr(str, value, num)) != NULL) {
num -= (pos - str);
str = pos + 1;
++count;
}
return count;
}
#define X(_str, chr) printf(_str " contains %c %zu times\n", chr, cntchr(_str, chr))
#define XN(_str, chr) printf(_str " contains %c %zu times\n", chr, cntnchr(_str, chr, strlen(_str)))
int main() {
X("nata", 'a');
X("Zzattackzaazzzz", 'z');
XN("nata", 'a');
XN("Zzattackzaazzzz", 'z');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment