c++_string中的中文字符
·
电脑系统中的英文字符串和中文字符最根本的区别就在于:
1、英文的 ASCII 码,其最高位为 0,占一个字节
注:英文的ASCII码范围是在0到127,二进制为(0000 0000 ~ 0111 1111)
2、中文的 ASCII 码,其最高位为 1,占两个字节。
#include <iostream>
int main()
{
std::string str = "ab你好!";
char szchinese[5] = { 0 };
printf("str.length:%d\n", str.length());
printf("str.size:%d\n", str.size());
//int i = 0;
for (int i=0; i < str.length();)
{
//不是全角字符
if (str[i] >= 0 && str[i] <= 127)
{
std::cout << "ascii:" << int(str[i]) << std::endl;
std::cout << str[i] << " 是英文" << std::endl;
i = i + 1;
}
else
{
//中文是2个字节
szchinese[0] = str[i], szchinese[1] = str[i + 1];
std::cout << "ascii:" << int(str[i]) << " ascii:" << int(str[i+1]) << std::endl;
std::cout << szchinese << " 是中文" << std::endl;
i = i + 2;
}
}
system("pause");
return 0;
}
运行结果:

上述代码,可以发现,中文字符占有两个char,每个char字符的8位二进制的首位都为1。
更多推荐
所有评论(0)