C++ objc-字符串编码转换.md

最近碰到字符串编码转换的问题,简单记录下

Ascii 转unicode

std::wstring AsciiToWide(std::string _strSrc)
{
    NSString *_nsstr = [NSString stringWithCString:_strSrc.c_str() encoding:NSASCIIStringEncoding];
    NSString *urlStringUTF8 = [_nsstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    const char* _cdata = [urlStringUTF8 cStringUsingEncoding:NSUnicodeStringEncoding];
    std::wstring _wstr((wchar_t*)_cdata);
    return _wstr;
}

unicode 转 Ascii

std::string  WideToAscii(std::wstring _strSrc)
{
    wchar_t* _csrc = const_cast<wchar_t*>(_strSrc.c_str());
    NSString *_nsstr = [NSString stringWithCString:(char*)_csrc encoding:NSUnicodeStringEncoding];
    NSString *urlStringUTF8 = [_nsstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    const char* _cdata = [urlStringUTF8 cStringUsingEncoding:NSASCIIStringEncoding];
    std::string _str(_cdata);
    return _str;
}

utf8 转 Ascii

std::string  UTF8ToAscii(std::string _strSrc)
{
    NSString *_nsstr = [NSString stringWithCString:_strSrc.c_str() encoding:NSUTF8StringEncoding];
    NSString *urlStringUTF8 = [_nsstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    const char* _cdata = [urlStringUTF8 cStringUsingEncoding:NSUTF8StringEncoding];
    std::string _str(_cdata);
    return _str;
}

Ascii 转 utf8

std::string  AsciiToUTF8(std::string _strSrc)
{
    NSString *_nsstr = [NSString stringWithCString:_strSrc.c_str() encoding:NSASCIIStringEncoding];
    NSString *urlStringUTF8 = [_nsstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    const char* _cdata = [urlStringUTF8 cStringUsingEncoding:NSUTF8StringEncoding];
    std::string _str(_cdata);
    return _str;
}

深圳利程电子有限公司


   转载规则


《C++ objc-字符串编码转换.md》 smoking 采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
  目录