wchar_t,char,string,wstring之間的相互轉(zhuǎn)換
在處理中文時(shí)有時(shí)需要進(jìn)行wchar_t,char,string,wstring之間的轉(zhuǎn)換。
其中char和string之間、wchar_t和wstring之間的轉(zhuǎn)換較為簡單,代碼在vs2010下測試通過。
#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>
using namespace std;
//Converting a WChar string to a Ansi string
char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)
{
int nlength=wcslen(pwstr);
//獲取轉(zhuǎn)換后的長度
int nbytes = WideCharToMultiByte( 0, 0, pwstr, nlength, NULL,0,NULL, NULL );
if(nbytes>len) nbytes=len;
// 通過以上得到的結(jié)果,轉(zhuǎn)換unicode 字符為ascii 字符
WideCharToMultiByte( 0,0, pwstr, nlength, pcstr, nbytes, NULL, NULL );
return pcstr ;
}
int main(){
setlocale(LC_ALL,"chs");
char* cc = "this is a char 測試";
wchar_t* wcc = L"this is a wchar 測試";
string str("this is a string 測試 ");
wstring wstr = L"this is a wstring 測試";
//string to char
const char* char_test = str.c_str();
//cout<<"char_test:"<<char_test<<endl;
//char to string
string ss = cc;
//cout<<"ss is :"<<ss<<endl;
//wstring to wchar
const wchar_t* wchar_test = wstr.c_str();
//wcout<<wchar_test<<endl;
//wchar to wstring
wstring wss = wcc;
wcout<<wcc<<endl;
//char to wchar_t
wchar_t *wc = new wchar_t[str.size()+1];
//swprintf(wc,L"%S",cc);
//wcout<<cc<<endl;
delete []wc;
// wchar_t to char
char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(wcc)+1));
memset(pcstr , 0 , 2 * wcslen(wcc)+1 );
w2c(pcstr,wcc,2 * wcslen(wcc)+1) ;
free(pcstr);
system("pause");
return 1;
}
上一篇:C/C++指針小結(jié)
欄 目:C語言
本文標(biāo)題:wchar_t,char,string,wstring之間的相互轉(zhuǎn)換
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/4035.html
您可能感興趣的文章
- 01-10使用C語言遞歸與非遞歸實(shí)現(xiàn)字符串反轉(zhuǎn)函數(shù)char *reverse(char *str
- 01-10探討編寫int strlen(char *strDest);不允許定義變量的問題
- 01-10基于C語言string函數(shù)的詳解
- 01-10用C++實(shí)現(xiàn)strcpy(),返回一個char*類型的深入分析
- 01-10深入理解c++中char*與wchar_t*與string以及wstring之間的相互轉(zhuǎn)換
- 01-10淺談C++中的string 類型占幾個字節(jié)
- 01-10c_str()的用法詳細(xì)解析
- 01-10c字符串,string對象,字符串字面值的區(qū)別詳解
- 01-10string中c_str(),data(),copy(p,n)函數(shù)的用法總結(jié)
- 01-10淺析string類字符串和C風(fēng)格字符串之間的區(qū)別


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達(dá)式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求