以前写的一些代码里有中文字符串,最近有些奇怪问题,所以研究了一下。
#include<iostream>
using namespace std;
int main()
{
std::string zh_str = "中文";
auto s = zh_str.c_str();
auto len = zh_str.size();
for (int i = 0; i < len; ++i)
{
int t = (char)s[i];
cout << "[" << i << "]:" << hex << t << endl;
}
}
在win上用vs和Ubuntu上用g++编译运行了一下,结果总结如下:
文件编码 | win | Ubuntu |
---|---|---|
gb2312 | 4 | 4 |
带签名utf-8 | 4 | 6 |
不带签名utf-8 | 6 | 6 |
4表示输出4个字节,6表示输出6个字节。win的vs在“不带签名utf-8"时,不能确定是什么编码,没有对“中文”处理,中文还是6个字节。有签名的,确认是utf-8,会处理成gb码编译。我用的win是中文版,用其他版本会有不同。
为了避免不确定问题,代码里不要直接用中文字符串。
std::string zh_str = "中文"; //不要这样搞。
std::string zh_str = "\xd6\xd0\xce\xc4"; //中文,要跟gb码字符串比较。
std::string zh_str = "\xe4\xb8\xad\xe6\x96\x87"; //中文,要跟utf-8字符串比较。
代码里不要采用第一种方式,用后面两种方式。
需要确认对比的字符串编码。
如果不知道编码,不要去做比较了,没有意义的。