Jan*_*mek 7 unicode utf-8 c++11
我试图迭代UTF-8字符串.我理解的问题是UTF-8字符具有可变长度,所以我不能只迭代char-by-char但我必须使用某种转换.我确信在现代C++中有一个功能,但我不知道它是什么.
#include <iostream>
#include <string>
int main()
{
std::string text = u8"?abcd?";
std::cout << text << std::endl; // Prints fine
std::cout << "First letter is: " << text.at(0) << text.at(1) << std::endl; // Again fine. So '?' is a 2 byte letter?
for(auto it = text.begin(); it < text.end(); it++)
{
// Obviously wrong. Outputs only ascii part of the text (a, b, c, d) correctly
std::cout << "Iterating: " << *it << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
编译 clang++ -std=c++11 -stdlib=libc++ test.cpp
从我读过的wchar_t,wstring不应该使用.
正如 nm 建议的那样,我使用了std::wstring_convert:
#include <codecvt>\n#include <locale>\n#include <iostream>\n#include <string>\n\nint main()\n{\n std::u32string input = U"\xc5\x99abcd\xc4\x9b";\n\n std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;\n\n for(char32_t c : input)\n {\n std::cout << converter.to_bytes(c) << std::endl;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n也许我应该在问题中更清楚地指定,我想知道这是否可以在 C++11 中完成,而不使用任何第三方库(如 ICU 或 UTF8-CPP)。
\n| 归档时间: |
|
| 查看次数: |
3736 次 |
| 最近记录: |