C++ 、objc 字符串编码转换

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

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(_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 字符串编码转换)