我们知道在字符串文字中,"\ 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 ?
Run Code Online (Sandbox Code Playgroud)
我想转换s1所以也cout << s1 << endl;将输出?.
有什么建议吗?
事实上,转换有点复杂。
\n\nstring s2 = "\\u94b1";\nRun Code Online (Sandbox Code Playgroud)\n\n实际上相当于:
\n\nchar cs2 = { 0xe9, 0x92, 0xb1, 0}; string s2 = cs2;\nRun Code Online (Sandbox Code Playgroud)\n\n这意味着您正在将其初始化为组成 \xe9\x92\xb1 的 UTF8 表示的 3 个字符 - 您只需检查s2.c_str()以确保这一点。
所以要处理6个原始字符\'\\\'、\'u\'、\'9\'、\'4\'、\'b\'、\'1\',必须先提取wchar_t从string s1 = "\\\\u94b1";(您阅读时得到的内容)。这很简单,只需跳过前两个字符并将其读取为十六进制:
unsigned int ui;\nstd::istringstream is(s1.c_str() + 2);\nis >> hex >> ui;\nRun Code Online (Sandbox Code Playgroud)\n\nui就是现在0x94b1。
现在,如果您有一个兼容 C++11 的系统,您可以使用以下命令进行转换std::convert_utf8:
wchar_t wc = ui;\nstd::codecvt_utf8<wchar_t> conv;\nconst wchar_t *wnext;\nchar *next;\nchar cbuf[4] = {0}; // initialize the buffer to 0 to have a terminating null\nstd::mbstate_t state;\nconv.out(state, &wc, &wc + 1, wnext, cbuf, cbuf+4, next);\nRun Code Online (Sandbox Code Playgroud)\n\ncbuf现在包含代表 utf8 中的 \xe9\x92\xb1 的 3 个字符和一个终止 null,你最终可以这样做:
string s3 = cbuf;\ncout << s3 << endl;\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |