Chapter Contents

Previous

Next
mblen

mblen



Determine Length of a Multibyte Character

Portability: ISO/ANSI C conforming


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTIONS
EXAMPLE


SYNOPSIS

#include <stdlib.h>

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


DESCRIPTION

mblen determines how many bytes are needed to represent the multibyte character pointed to by s .

n specifies the maximum number of bytes of the multibyte character sequence to examine.


RETURN VALUE

If s is not NULL , the return value is as follows:
0 is returned if s points to the null character.
length of the multibyte character is returned if the next n            
-1 is returned if the next n or fewer bytes do not constitute a valid multibyte character.

If s is NULL , the return value is as follows:
nonzero value is returned if the current locale supports state-dependent encodings.
0 is returned if the current locale does not support state-dependent encodings.
 


CAUTIONS

A diagnostic is not issued if mblen encounters invalid data; a return value of -1 is the only indication of an error.


EXAMPLE

   /* This example counts multibyte characters (not including   */
   /* terminating null) in a DBCS mixed string using mblen().   */

#include <locale.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
   /* "strptr" points to the beginning of a DBCS MIXED string.  */
   /* RETURNS: number of multibyte characters                   */
int count1(char *strptr)
{
   int i = 0;          /* number of multibyte characters found  */
   int charlen;        /* byte length of current characte       */

   /* Inform library that we will be accepting a DBCS string.   */
   /* That is, SO and SI are not regular control characters:    */
   /* they indicate a change in shift state.                    */
   setlocale(LC_ALL, "dbcs");
      /* Reset to initial shift state. (A valid mixed string    */
      /* must begin in initial shift state).                    */
   mblen(NULL, 0);

     /* One loop iteration per character. Advance "strptr" by   */
     /* number of bytes consumed.                               */
   while (charlen = mblen(strptr, MB_LEN_MAX)) {
      if (charlen < 0) {
         fputs("Invalid MIXED DBCS string", stderr);
         abort();
         fclose(stderr);
      }
      strptr += charlen;
      i++;
   }
   return i;
}


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.