获取 std::wstring 的子字符串

2024-01-06

我怎样才能得到a的子串std::wstring其中包含一些非 ASCII 字符?

以下代码不会输出任何内容:
(文本是一个阿拉伯单词,包含 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;
}

这应该有效:住在科利鲁 http://coliru.stacked-crooked.com/view?id=1a98e0a9bbda086ddaf980a637c1a9ab-93e6c6235a92d0c233f44beab03470ad

#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不过,我认为你的substring电话做出了奇怪的假设。 让我立即提出解决方案:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 std::wstring 的子字符串 的相关文章

随机推荐