读书人

求包含汉字的字符串长度解决方案

发布时间: 2012-04-06 12:22:24 作者: rapoo

求包含汉字的字符串长度

C/C++ code
char a[] = "中国abcd";


用strlen(a); 求得的结果是8;
我要把汉字都算做一个长度,即要求的结果是6,应该用哪个函数?谢谢~~~

用C语言实现。

[解决办法]
C/C++ code
    char a[] = "中国abcd";    setlocale(LC_ALL,"");    int count=mbstowcs(NULL,a,strlen(a));
[解决办法]
C/C++ code
#include "stdio.h"#include "stdlib.h"int main(){    char a[] = "中国abcd";    int i=0,b;    double count=0.0;    while(a[i])    {        b=128&((int)a[i]);        if(b==128) count+=0.5;        else count++;        i++;            }printf("%d",(int)count);    return 0;}
[解决办法]
#include <windows.h>

int aLen = MultiByteToWideChar(CP_ACP, NULL, a, strlen(a), NULL, 0);

读书人网 >C语言

热点推荐