getting a sub string of a std::wstring

我的梦境 提交于 2019-12-22 13:47:42

问题


How can I get a substring of a std::wstring which includes some non-ASCII characters?

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;
}

回答1:


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;
}

Prints

سلا
 hell

Frankly though, I think your substring calls are making weird assumptions. Let me suggest a fix for that in a minute:



来源:https://stackoverflow.com/questions/18323876/getting-a-sub-string-of-a-stdwstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!