Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does strlen count unicode in c

I'm curious as to how strlen count unicode characters of multiple bytes in C.

Does it count each byte or character (as they can consist of several bytes) until first '\0'?

like image 311
Horse SMith Avatar asked Nov 23 '14 08:11

Horse SMith


Video Answer


2 Answers

strlen() counts number of bytes until a \0 is encountered. This holds true for all strings.

For Unicode, note that the return value of strlen() may be affected by the possible existing \0 byte in a valid character other than the null terminator. If UTF-8 is used, it's fine because no valid character other than ASCII 0 can have a \0 byte, but it may not be true for other encodings.

like image 101
Yu Hao Avatar answered Sep 28 '22 11:09

Yu Hao


strlen only applies to strings, that is null terminated arrays of char. All multibyte encodings that are permitted inside strings have the property that they contain no internal null bytes, so strlen and other str functions such as strcat work fine.

If by "unicode" you mean arrays of wchar_t then this can contain null bytes, but here again this is no problem, none of the wchar_t elements itself will be null. And you shouldn't apply the str functions to such arrays, they are not defined for them.

like image 22
Jens Gustedt Avatar answered Sep 28 '22 11:09

Jens Gustedt