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)換較為簡(jiǎn)單,代碼在vs2010下測(cè)試通過(guò)。
#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)換后的長(zhǎng)度
int nbytes = WideCharToMultiByte( 0, 0, pwstr, nlength, NULL,0,NULL, NULL );
if(nbytes>len) nbytes=len;
// 通過(guò)以上得到的結(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 測(cè)試";
wchar_t* wcc = L"this is a wchar 測(cè)試";
string str("this is a string 測(cè)試 ");
wstring wstr = L"this is a wstring 測(cè)試";
//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;
}
相關(guān)文章
C語(yǔ)言二維數(shù)組運(yùn)用實(shí)現(xiàn)掃雷游戲
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言二維數(shù)組運(yùn)用實(shí)現(xiàn)掃雷游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06java 中ArrayList與LinkedList性能比較
這篇文章主要介紹了java 中ArrayList與LinkedList性能比較的相關(guān)資料,需要的朋友可以參考下2017-03-03詳解基于C++實(shí)現(xiàn)約瑟夫環(huán)問(wèn)題的三種解法
約瑟夫環(huán)問(wèn)題是算法中相當(dāng)經(jīng)典的一個(gè)問(wèn)題,其問(wèn)題理解是相當(dāng)容易的,并且問(wèn)題描述有非常多的版本,并且約瑟夫環(huán)問(wèn)題還有很多變形,通過(guò)這篇約瑟夫問(wèn)題的講解,一定可以帶你理解透徹2021-06-06linux根據(jù)pid獲取進(jìn)程名和獲取進(jìn)程pid(c語(yǔ)言獲取pid)
status文件,第一行的Name即為進(jìn)程名,C程序?qū)崿F(xiàn)根據(jù)PID獲取進(jìn)程名和根據(jù)進(jìn)程名獲取PID,大家參考使用吧2013-12-12C語(yǔ)言字符串函數(shù)介紹與模擬實(shí)現(xiàn)詳解
這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)字符串操作函數(shù)的實(shí)例的相關(guān)資料,開(kāi)發(fā)程序的時(shí)候經(jīng)常使用到一些字符串函數(shù),例如求字符串長(zhǎng)度,拷貝字符串……,需要的朋友可以參考下2021-09-09