首页 > 学院 > 开发设计 > 正文

string和wstring互转、全角半角互转

2019-11-10 18:13:57
字体:
来源:转载
供稿:网友

string和wstring互转、全角半角互转

一.string和wstring互转

static std::string wstringTostring(const std::wstring& ws)

{

    std::string curLocale =setlocale(LC_ALL, NULL);

    setlocale(LC_ALL,"chs");

    const wchar_t* _Source =ws.c_str();

    size_t _Dsize = 2 *ws.size()+2;

    char *_Dest = newchar[_Dsize];

    memset(_Dest,0,_Dsize);

   wcstombs(_Dest,_Source,_Dsize);

    std::string result =_Dest;

    if(_Dest)

    {

        delete []_Dest;

        _Dest = NULL;

    }

    setlocale(LC_ALL,curLocale.c_str());

 

    return result;

}

 

static std::wstring stringTowstring(string& str)

{

    std::string curLocal =setlocale(LC_ALL, NULL);

    setlocale(LC_ALL,"chs");

    const char* _Source  = str.c_str();

    size_t _Dsize =2*str.size() + 2;

    wchar_t *_Dest = newwchar_t[_Dsize];

    memset(_Dest, 0x0,_Dsize);

    mbstowcs(_Dest, _Source,_Dsize);

    std::wstring result =_Dest;

    if(_Dest)

    {

        delete []_Dest;

        _Dest = NULL;

    }

    setlocale(LC_ALL,curLocal.c_str());

 

    return result;

}

 

二.宽字符全角半角互转

//UTF-8:是Unicode字符的实现方式之一,它使用1-4个字符表示一个符号,

//根据不同的符号而变化字节长度。

using namespace std;

std::wstring FullToHalf(std::wstring str)

{

    const int nStrLen =str.size() + 2;

 

    wchar_tinputWchar[nStrLen];

    memset(inputWchar, 0x0,sizeof(wchar_t)*nStrLen);

    memcpy(inputWchar,str.c_str(), sizeof(wchar_t)*nStrLen);

 

    for(int i = 0; i <nStrLen; i++)

    {

        if (inputWchar[i]>= 0xff01 && inputWchar[i] <= 0xff7e)

        {

            inputWchar[i] -=65248;

        }

        else if (inputWchar[i]== 12288)

        {

            inputWchar[i] = '';

        }

        else if (inputWchar[i]>= 0x00a4 && inputWchar[i] <= 0x3017)

        {

            inputWchar[i] = '';

        }

    }

 

    wstring halfString;

   halfString.resize(nStrLen);

    halfString = inputWchar;

 

    return halfString;

}

std::wstring HalfToFull(std::wstring str)

{

    const int nStrLen =str.size() + 2;

 

    wchar_tinputWchar[nStrLen];

    memset(inputWchar, 0x0,sizeof(wchar_t)*nStrLen);

    memcpy(inputWchar,str.c_str(), sizeof(wchar_t)*nStrLen);

 

    for(int i = 0; i <nStrLen; i++)

    {

        if (inputWchar[i]>= 0x0021 && inputWchar[i] <= 0x009e)

        {

            inputWchar[i] +=65248;

        }

        else if (inputWchar[i]== 32)

        {

            inputWchar[i] =12288;

        }

    }

 

    wstring fullString;

   fullString.resize(nStrLen);

    fullString = inputWchar;

 

    return fullString;

}

 

三.测试

    wstring half = L"中国1";//UTF8-half

    wstring full = L"中国1";//UTF8-full

    string strTemp = "中1国";

 

    wstring conhalf = FullToHalf(full);

    wstring confull =HalfToFull(half);

 

    wstring wstringTemp =stringTowstring(strTemp);

    string stringTemp =wstringTostring(wstringTemp);


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表