C++字符串:string and wstring的区别

来源:互联网 发布:linux系统安全 编辑:程序博客网 时间:2024/05/17 07:09

C++字符串:string and wstring的区别,非常重要!!!!

请看下面代码:

wstring s=L"abc,?重庆大学机械传动国家重点实验室,重庆,400044";
 string s1="abc,?重庆大学机械传动国家重点实验室,重庆,400044";

cout<<"窄字符串模式下的长度"<<s1.size()<<endl;
 cout<<"宽字符串模式下的长度"<<s.size()<<endl;

输出结果为:

可以看出在宽字符串模式下:一个全角字符和一个半角字符占有的计数单位相同;在窄字符串模式下,一个全角字符的计算单位是一个半角字符计数单位的两倍。



C++ STRING 和WSTRING 之间的互相转换函数

#include <string>std::string ws2s(const std::wstring& ws){    std::string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";    setlocale(LC_ALL, "chs");    const wchar_t* _Source = ws.c_str();    size_t _Dsize = 2 * ws.size() + 1;    char *_Dest = new char[_Dsize];    memset(_Dest,0,_Dsize);    wcstombs(_Dest,_Source,_Dsize);    std::string result = _Dest;    delete []_Dest;    setlocale(LC_ALL, curLocale.c_str());    return result;}std::wstring s2ws(const std::string& s){    setlocale(LC_ALL, "chs");     const char* _Source = s.c_str();    size_t _Dsize = s.size() + 1;    wchar_t *_Dest = new wchar_t[_Dsize];    wmemset(_Dest, 0, _Dsize);    mbstowcs(_Dest,_Source,_Dsize);    std::wstring result = _Dest;    delete []_Dest;    setlocale(LC_ALL, "C");    return result;}


原创粉丝点击