获取std :: wstring的子字符串 [英] getting a sub string of a std::wstring
本文介绍了获取std :: wstring的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得包含一些非ASCII字符的 std :: wstring
的子字符串?
How can I get a substring of a std::wstring
which includes some non-ASCII characters?
以下代码不会输出任何内容:
(文本是一个阿拉伯字包含4个字符,每个字符有两个字节,加上Hello字样)
The following code does not output anything:
(The text is an Arabic word contains 4 characters where each character has two bytes, plus the word "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;
}
推荐答案
This should work: 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
strong>虽然,我认为你的 substring
调用做奇怪的假设。让我在一分钟内建议修正:
Frankly though, I think your substring
calls are making weird assumptions. Let me suggest a fix for that in a minute:
这篇关于获取std :: wstring的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文