如何获取包含一些非 ASCII 字符的 std::wstring
的子字符串?
以下代码不输出任何内容:
(文字是一个阿拉伯语单词,包含4个字符,每个字符有两个字节,加上单词“Hello”)
#include <iostream>
#include <string>
using namespace std;
int main()
{
wstring s = L"سلام hello";
wcout << s.substr(0,3) << endl;
wcout << s.substr(4,5) << endl;
return 0;
}
最佳答案
这应该有效: live on Coliru
#include <iostream>
#include <string>
#include <boost/regex/pending/unicode_iterator.hpp>
using namespace std;
template <typename C>
std::string to_utf8(C const& in)
{
std::string result;
auto out = std::back_inserter(result);
auto utf8out = boost::utf8_output_iterator<decltype(out)>(out);
std::copy(begin(in), end(in), utf8out);
return result;
}
int main()
{
wstring s = L"سلام hello";
auto first = s.substr(0,3);
auto second = s.substr(4,5);
cout << to_utf8(first) << endl;
cout << to_utf8(second) << endl;
}
打印
سلا
hell
坦率地说 不过,我认为您的 substring
调用做出了奇怪的假设。 让我在一分钟内提出修复建议:
关于c++ - 获取 std::wstring 的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18323876/