Created
October 1, 2015 18:24
-
-
Save mmitou/e6ae682fe5cb08c8a718 to your computer and use it in GitHub Desktop.
utf8文字数カウント
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| int byte_size(const unsigned char c) { | |
| if(c <= 0x7f) { | |
| return 1; | |
| } else if(0xc2 <= c && c <= 0xdf) { | |
| return 2; | |
| } else if(0xe0 <= c && c <= 0xef) { | |
| return 3; | |
| } else if(0xf0 <= c && c <= 0xff) { | |
| return 4; | |
| } else { | |
| return -1; | |
| } | |
| } | |
| int length(const unsigned char s[], const int size) { | |
| int count = 0; | |
| int i = 0; | |
| for(i = 0; i < size;) { | |
| const int bytes = byte_size(s[i]); | |
| if(bytes < 0) { | |
| break; | |
| } else { | |
| count++; | |
| i+= bytes; | |
| } | |
| } | |
| return count -1; | |
| } | |
| int main() { | |
| unsigned char s[] = "あいうえお鬼の葛餅 🔣✔"; | |
| int l = length(s, sizeof(s)); | |
| printf("length(%s) = %d\n", s, l); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment