问题
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'?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/27086943/how-does-strlen-count-unicode-in-c