how does strlen count unicode in c

6.5k views Asked by At

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'?

2

There are 2 answers

2
Yu Hao On BEST ANSWER

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.

0
Jens Gustedt On

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.