Length of a string displayable in C
Does anyone know if there is a function in lib or libX11 which returns the number of characters? (strlen () is not appropriate because it returns the number of bytes)
Eg "/hame/big/proj$", strlen () returns me 19 while only 15 characters 'to', 'é', 'i', 'O' which are 2octets characters.
I made a function:
Code:
unsigned int StringLength(char *str)
(
unsigned int nb;
char c, flg;
for (nb = 0, flg = 0; (c = *str) != '\0'; ++str, ++pos) {
if (isprint(c) != 0){ // classical character display
flg = 0;
++nb;
)
else if (flg == 0) // if it was the first byte of a 2octets character
++flg;
else if (flg == 1) { // 2nd characters display the 2octets
++nb;
flg = 0;
)
)
if (flg == 1) // If the last character was the 2nd byte character 2octets
++nb;
return (nb);
)
Re: Length of a string displayable in C
it's utf8:
Code:
size_t strlen_utf8 (const char * const s)
(
size_t i = 0;
size_t j = 0;
while (s[i])
(
if ((s[i] & 0xc0) != 0x80)
j++;
i++;
)
return j;
)
Re: Length of a string displayable in C
If your string is a wide char (wchar_t-based), the function is wcslen
If your string is encoded in utf8 mblen should do the trick.
Re: Length of a string displayable in C
What a solution... Wow. Thank you.