C programming mblen stdlib.h


int mblen(const char *s , size_t n);

In C programming the <stdlib.h> mblen function determines the number of bytes contained in the multibyte character pointed to by s.Only the first ‘n’ number of characters are examined at a time.

Parameters:
s -The string whose length is to be determined.

n -The number of characters whose size is to be examine.

Return type
int
   a) It return the number of byte of characters examine by ‘n’.
   b)If ‘str’ is null, then mblen( ) returns non-zero if multibyte characters have state-dependent encodings.
   c) Return ​0​ if s is pointing at the null charcter ‘\0’.
   d) It returns –1 on error.

The number of byes of the multibyte string can be determine by the sum of all the byte return by the function.

Calling this function change the conversion state.It can however, be reset by calling.

mblwn( NULL , 0 );

Code example

char c[]=”New string” ;
int i=0 , ret ;

while( c[i] )
{
ret=mblen( &c[i] , 1 ) ;
if( ret==-1 ) break ;
i++ ;
}

printf( “Number of bytes =%i” , i) ;

Output

Number of bytes =10

Since there are 10 characters in ‘c’ string the number of bytes is 10.

Another example is shown below when UTF-8 characters is passed.

char c[]=u8″\u0085\u0d2a\u0b23″ ;
int i=0 , ret ;

mblen( NULL , 0 ); //resetting the state

while( c[i] )
{
ret=mblen( &c[i] , 1 );

if( ret==-1 ) break;

i++;
}

printf(“Number of bytes =%i” , i) ;

Output

Number of bytes =8
 


*Side Note

The ‘mblen’ function is equivalent to

   mbtowc((wchar_t *)0 , s , n);
 


Related links

->C mbtowc stdlib.h

->C wctomb stdlib.h