C programming stdlib.h function - int mblen(const char *str, size_t n)

‮ww‬w.theitroad.com

The mblen() function is a standard library function in C programming language that determines the number of bytes needed to represent the first character of a multi-byte sequence.

The function takes two arguments: a pointer to a string containing the multi-byte sequence to be examined, and a size_t value n, which specifies the maximum number of bytes to examine in the input string. The function returns an integer value indicating the number of bytes used to represent the first character in the input string.

If the input string is not a valid multi-byte character sequence, the mblen() function returns a value of -1.

Here's an example usage of the mblen() function:

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>

int main() {
  char mbstr[] = "こんにちは"; // a Japanese greeting "Konnichiwa"
  int len = mblen(mbstr, MB_CUR_MAX);
  printf("The length of the first character in the multi-byte string is %d\n", len);
  return 0;
}

In this example, the mblen() function is used to determine the number of bytes used to represent the first character of the multi-byte string mbstr. The value of MB_CUR_MAX is used as the second argument to mblen(), which specifies the maximum number of bytes to examine in the input string.

The mblen() function is part of the wide-character support library in C, and is often used in conjunction with other wide-character functions such as mbtowc() and wctomb().