假设您的 Linux 环境使用 UTF-8 编码,那么以下代码将使您的程序准备好在 C++ 中轻松进行 Unicode 处理:
int main(int argc, char * argv[]) {
std::setlocale(LC_CTYPE, "");
// ...
}
接下来,wchar_t 类型在 Linux 中是 32 位的,这意味着它可以保存单独的 Unicode 代码点,您可以安全地使用 wstring 类型在 C++ 中进行经典字符串处理(逐个字符)。使用上面的 setlocale 调用,插入到 wcout 将自动将您的输出转换为 UTF-8,从 wcin 提取将自动将 UTF-8 输入转换为 UTF-32(1 个字符 = 1 个代码点)。剩下的唯一问题是 argv[i] 字符串仍然是 UTF-8 编码的。
您可以使用以下函数将 UTF-8 解码为 UTF-32。如果输入字符串损坏,它将返回正确转换的字符,直到 UTF-8 规则被破坏的地方。如果您需要更多错误报告,您可以改进它。但是对于 argv 数据,可以安全地假设它是正确的 UTF-8:
#define ARR_LEN(x) (sizeof(x)/sizeof(x[0]))
wstring Convert(const char * s) {
typedef unsigned char byte;
struct Level {
byte Head, Data, Null;
Level(byte h, byte d) {
Head = h; // the head shifted to the right
Data = d; // number of data bits
Null = h << d; // encoded byte with zero data bits
}
bool encoded(byte b) { return b>>Data == Head; }
}; // struct Level
Level lev[] = {
Level(2, 6),
Level(6, 5),
Level(14, 4),
Level(30, 3),
Level(62, 2),
Level(126, 1)
};
wchar_t wc = 0;
const char * p = s;
wstring result;
while (*p != 0) {
byte b = *p++;
if (b>>7 == 0) { // deal with ASCII
wc = b;
result.push_back(wc);
continue;
} // ASCII
bool found = false;
for (int i = 1; i < ARR_LEN(lev); ++i) {
if (lev[i].encoded(b)) {
wc = b ^ lev[i].Null; // remove the head
wc <<= lev[0].Data * i;
for (int j = i; j > 0; --j) { // trailing bytes
if (*p == 0) return result; // unexpected
b = *p++;
if (!lev[0].encoded(b)) // encoding corrupted
return result;
wchar_t tmp = b ^ lev[0].Null;
wc |= tmp << lev[0].Data*(j-1);
} // trailing bytes
result.push_back(wc);
found = true;
break;
} // lev[i]
} // for lev
if (!found) return result; // encoding incorrect
} // while
return result;
} // wstring Convert