C++ cstdlib mblen


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

The C++ <cstdlib> 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” ;
int i=0 , ret ;

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

cout<< “Number of bytes =” << i ;

Output

Number of bytes =3

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

Code example

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++;
}

cout<< “Number of bytes =” << i ;

Output

Number of bytes =8
 


*Side Note

The ‘mblen’ function is equivalent to

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

Link : C++ cstdlib mbtowc function