在Windows下,中文字符在C++中的内存占用为2字节,此时采用字符串长度获取函数得到的结果会将一个中文字符识别为两个长度:
#include#include using namespace std; int main() { int len; char str1[50]; strcpy(str1,"abc中文def");//赋值 len = strlen(str1); printf("字符串的长度为%d",len); //使用strlen函数获取长度,结果为10 string str2 = "abc中文def"; len = str2.length();//也可以用len = str2.size(); printf("字符串的长度为%d",len); //使用string类的长度获取函数length(),结果为10 len = sizeof(str1)/(char); printf("字符串的长度为%d",len); //使用sizeof运算符获取占用的内存,结果为10 }
而实际上,字符串的长度为8,并非上述方法的结果10。那么,如何获取真正的长度呢?
其实,我们不妨试试中文字符的值:
char a = '中'; std::cout << (int) a;
输出结果为:-48。
试试其他中文字符,也都是负数。
依据这一点,我们便可以做出一个获取含有中文的字符串长度的函数:
int lengthOfStr(string str)
{
int count = 0;
for (int i = 0; str[i]; i++)
{
if (str[i] < 0) i++;
//负数说明该字符为中文字符,占用两个字节,跳过后一个字节(i++),不进行统计
count++;
}
return count;
}
用前面的示例验证:
#include#include using namespace std; int lengthOfStr(string str) { int count = 0; for (int i = 0; str[i]; i++) { if (str[i] < 0) i++; count++; } return count; } int lengthOfStr_c(char str[]) { int count = 0; for (int i = 0; str[i]; i++) { if (str[i] < 0) i++; count++; } return count; } int main() { int len; char str1[50] = "abc中文def"; string str2 = "abc中文def"; len = lengthOfStr_c(str1); printf("字符串的长度为%d",len); len = lengthOfStr(str2); printf("字符串的长度为%d",len); }
输出结果均为8。



