您的位置:首页 > 编程语言 > C语言/C++

C++中各种string的相互转化

2015-04-08 11:13 295 查看
转自:http://blog.chinaunix.net/uid-18872995-id-302626.html

因工作需要要进行LPCWSTR和string的转换,到网上搜出一篇详细介绍的文章出来了,本着“拿来主义”做个技术积累。

一 C++ 中 string与wstring互转

方法一:


string WideToMutilByte(const wstring& _src)






{


int nBufSize = WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, NULL, 0, 0, FALSE);



char *szBuf = new char[nBufSize];



WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, szBuf, nBufSize, 0, FALSE);



string strRet(szBuf);



delete []szBuf;


szBuf = NULL;



return strRet;


}



wstring MutilByteToWide(const string& _src)






{


//计算字符串 string 转成 wchar_t 之后占用的内存字节数


int nBufSize = MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,NULL,0);




//为 wsbuf 分配内存 BufSize 个字节


wchar_t *wsBuf = new wchar_t[nBufSize];



//转化为 unicode 的 WideString


MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,wsBuf,nBufSize);



wstring wstrRet(wsBuf);



delete []wsBuf;


wsBuf = NULL;



return wstrRet;


}


#include <string>


#include <windows.h>


using namespace std;


//Converting a WChar string to a Ansi string


std::string WChar2Ansi(LPCWSTR pwszSrc)






{


int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);




if (nLen<= 0) return std::string("");




char* pszDst = new char[nLen];


if (NULL == pszDst) return std::string("");




WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);


pszDst[nLen -1] = 0;




std::string strTemp(pszDst);


delete [] pszDst;




return strTemp;


}






string ws2s(wstring& inputws)






{


return WChar2Ansi(inputws.c_str());


}





//Converting a Ansi string to WChar string


std::wstring Ansi2WChar(LPCSTR pszSrc, int nLen)








{


int nSize = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pszSrc, nLen, 0, 0);


if(nSize <= 0) return NULL;




WCHAR *pwszDst = new WCHAR[nSize+1];


if( NULL == pwszDst) return NULL;




MultiByteToWideChar(CP_ACP, 0,(LPCSTR)pszSrc, nLen, pwszDst, nSize);


pwszDst[nSize] = 0;




if( pwszDst[0] == 0xFEFF) // skip Oxfeff


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


pwszDst[i] = pwszDst[i+1];




wstring wcharString(pwszDst);


delete pwszDst;




return wcharString;


}






std::wstring s2ws(const string& s)






{


return Ansi2WChar(s.c_str(),s.size());


}





第二种方法:采用ATL封装_bstr_t的过渡:(注,_bstr_是Microsoft Specific的,所以下面代码可以在VS2005通过,无移植性);


#include <string>


#include <comutil.h>


using namespace std;


#pragma comment(lib, "comsuppw.lib")




string ws2s(const wstring& ws);


wstring s2ws(const string& s);




string ws2s(const wstring& ws)






{


_bstr_t t = ws.c_str();


char* pchar = (char*)t;


string result = pchar;


return result;


}






wstring s2ws(const string& s)






{


_bstr_t t = s.c_str();


wchar_t* pwchar = (wchar_t*)t;


wstring result = pwchar;


return result;


}





第三种方法:使用CRT库的mbstowcs()函数和wcstombs()函数,平台无关,需设定locale。


#include <string>


#include <locale.h>


using namespace std;


string ws2s(const wstring& ws)






{


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);


string result = _Dest;


delete []_Dest;




setlocale(LC_ALL, curLocale.c_str());




return result;


}



wstring s2ws(const 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);


wstring result = _Dest;


delete []_Dest;


setlocale(LC_ALL, "C");



return result;


}

三 C++ 的字符串与C#的转化

1)将system::String 转化为C++的string:


// convert_system_string.cpp


// compile with: /clr


#include <string>


#include <iostream>


using namespace std;


using namespace System;






void MarshalString ( String ^ s, string& os )

{


using namespace Runtime::InteropServices;


const char* chars =


(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();


os = chars;


Marshal::FreeHGlobal(IntPtr((void*)chars));


}






void MarshalString ( String ^ s, wstring& os )

{


using namespace Runtime::InteropServices;


const wchar_t* chars =


(const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();


os = chars;


Marshal::FreeHGlobal(IntPtr((void*)chars));


}






int main()

{


string a = "test";


wstring b = L"test2";


String ^ c = gcnew String("abcd");




cout << a << endl;


MarshalString(c, a);


c = "efgh";


MarshalString(c, b);


cout << a << endl;


wcout << b << endl;


}



2)将System::String转化为char*或w_char*


// convert_string_to_wchar.cpp


// compile with: /clr


#include < stdio.h >


#include < stdlib.h >


#include < vcclr.h >




using namespace System;






int main()

{


String ^str = "Hello";




// Pin memory so GC can't move it while native function is called


pin_ptr<const wchar_t> wch = PtrToStringChars(str);


printf_s("%S\n", wch);




// Conversion to char* :


// Can just convert wchar_t* to char* using one of the


// conversion functions such as:


// WideCharToMultiByte()


// wcstombs_s()


//

etc


size_t convertedChars = 0;


size_t sizeInBytes = ((str->Length + 1) * 2);


errno_t err = 0;


char *ch = (char *)malloc(sizeInBytes);




err = wcstombs_s(&convertedChars,


ch, sizeInBytes,


wch, sizeInBytes);


if (err != 0)


printf_s("wcstombs_s failed!\n");




printf_s("%s\n", ch);


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: