获取std::wstring的子字符串

getting a sub string of a std::wstring

本文关键字:字符串 wstring std 获取      更新时间:2023-10-16

如何获取包含一些非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;
}

这应该有效:在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呼叫做出了奇怪的假设让我在一分钟内提出解决方案: