Convert between string, u16string & u32string

后端 未结 3 1493
清歌不尽
清歌不尽 2020-11-27 10:21

I\'ve been looking for a way to convert between the Unicode string types and came across this method. Not only do I not completely understand the method (there are no commen

3条回答
  •  伪装坚强ぢ
    2020-11-27 10:44

    I've written helper functions to convert to/from UTF8 strings (C++11):

    #include 
    #include 
    #include 
    
    using namespace std;
    
    template 
    string toUTF8(const basic_string, allocator>& source)
    {
        string result;
    
        wstring_convert, T> convertor;
        result = convertor.to_bytes(source);
    
        return result;
    }
    
    template 
    void fromUTF8(const string& source, basic_string, allocator>& result)
    {
        wstring_convert, T> convertor;
        result = convertor.from_bytes(source);
    }
    

    Usage example:

    // Unicode <-> UTF8
    {
        wstring uStr = L"Unicode string";
        string str = toUTF8(uStr);
    
        wstring after;
        fromUTF8(str, after);
        assert(uStr == after);
    }
    
    // UTF16 <-> UTF8
    {
        u16string uStr;
        uStr.push_back('A');
        string str = toUTF8(uStr);
    
        u16string after;
        fromUTF8(str, after);
        assert(uStr == after);
    }
    

提交回复
热议问题