Skip to content

Instantly share code, notes, and snippets.

@kaworu
Created July 21, 2016 14:34
Show Gist options
  • Save kaworu/9e99ee0f7bbe455bfa8eb2a018a1e10b to your computer and use it in GitHub Desktop.
Save kaworu/9e99ee0f7bbe455bfa8eb2a018a1e10b to your computer and use it in GitHub Desktop.
#include <string.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
size_t
nchars(const char *s)
{
size_t charlen, chars;
mbstate_t mbs;
chars = 0;
memset(&mbs, 0, sizeof(mbs));
while ((charlen = mbrlen(s, MB_CUR_MAX, &mbs)) != 0 &&
charlen != (size_t)-1 && charlen != (size_t)-2) {
s += charlen;
chars++;
}
return (chars);
}
int
main(int argc, char **argv)
{
setlocale(LC_ALL, "");
if (argc == 2) {
printf("%zu\n", nchars(argv[1]));
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment