gpt4 book ai didi

c++ - 如何将 "\u94b1"之类的字符串转换为 C++ 中的一个真实字符?

转载 作者:可可西里 更新时间:2023-11-01 16:09:43 25 4
gpt4 key购买 nike

我们知道在字符串文字中,“\u94b1”将被转换为一个字符,在本例中为中文单词“钱”。但是如果它是一个字符串中的 6 个字符,比如 '\'、'u'、'9'、'4'、'b'、'1',我如何手动将它转换为一个字符?

例如:

string s1;
string s2 = "\u94b1";
cin >> s1; //here I input \u94b1
cout << s1 << endl; //here output \u94b1
cout << s2 << endl; //and here output 钱

我要转换s1这样cout << s1 << endl;还将输出 .

有什么建议吗?

最佳答案

实际上转换要复杂一些。

string s2 = "\u94b1";

实际上等同于:

char cs2 = { 0xe9, 0x92, 0xb1, 0}; string s2 = cs2;

这意味着您正在将它初始化为组成钱的 UTF8 表示形式的 3 个字符 - 您只需检查 s2.c_str() 以确保这一点。


所以要处理 6 个原始字符 '\'、'u'、'9'、'4'、'b'、'1',您必须首先从 string s1 = "\\u94b1";(阅读时得到的)。很简单,只需要跳过前两个字符并将其读为十六进制:

unsigned int ui;
std::istringstream is(s1.c_str() + 2);
is >> hex >> ui;

ui 现在是 0x94b1

现在如果你有一个 C++11 兼容的系统,你可以用 std::convert_utf8 转换它:

wchar_t wc = ui;
std::codecvt_utf8<wchar_t> conv;
const wchar_t *wnext;
char *next;
char cbuf[4] = {0}; // initialize the buffer to 0 to have a terminating null
std::mbstate_t state;
conv.out(state, &wc, &wc + 1, wnext, cbuf, cbuf+4, next);

cbuf 现在包含在 utf8 中表示钱的 3 个字符和一个终止 null,您最终可以这样做:

string s3 = cbuf;
cout << s3 << endl;

关于c++ - 如何将 "\u94b1"之类的字符串转换为 C++ 中的一个真实字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37561796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com