當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 mblen()用法及代碼示例


描述

C庫函數int mblen(const char *str, size_t n)返回參數指向的 multi-byte 字符的長度str

聲明

以下是 mblen() 函數的聲明。

int mblen(const char *str, size_t n)

參數

  • str- 這是指向多字節字符的第一個字節的指針。

  • n- 這是要檢查字符長度的最大字節數。

返回值

如果識別出非空寬字符,則 mblen() 函數返回從 multi-byte 序列從 str 開始傳遞的字節數。如果識別出空寬字符,則返回 0。如果遇到無效的 multi-byte 序列或無法解析完整的 multi-byte 字符,則返回 -1。

示例

下麵的例子展示了 mblen() 函數的用法。

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

int main () {
   int len;
   char *pmbnull  = NULL;
   char *pmb = (char *)malloc( MB_CUR_MAX );
   wchar_t *pwc = L"Hi";
   wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t ));

   printf("Converting to multibyte string\n");
   len = wcstombs( pmb, pwc, MB_CUR_MAX);
   printf("Characters converted %d\n", len);
   printf("Hex value of first multibyte character:%#.4x\n", pmb);
   
   len = mblen( pmb, MB_CUR_MAX );
   printf( "Length in bytes of multibyte character %x:%u\n", pmb, len );
   
   pmb = NULL;
   
   len = mblen( pmb, MB_CUR_MAX );
   printf( "Length in bytes of multibyte character %x:%u\n", pmb, len );
   
   return(0);
}

讓我們編譯並運行上麵的程序,將產生以下結果 -

Converting to multibyte string
Characters converted 1
Hex value of first multibyte character:0x168c6010
Length in bytes of multibyte character 168c6010:1
Length in bytes of multibyte character 0:0

相關用法


注:本文由純淨天空篩選整理自 C library function - mblen()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。