VC多字节字符串和宽字节字符串转换

在VC编程中,wchar_t表示unicode字符类型,一个字符占两个字节,char则是ascii码类型,一个字符占一个字节。两者分别用在Unicode和ANSI编程环境下。下面是一组测试程序以及两者之间的转换程序,主要用到wcstombs以及mbstowcs函数。

#include<iostream>
#include<string>
#include<Windows.h>

using namespace std;

/**
*	LPWSTR 与 wchar_t* 等价 (wchar_t是C/C++的字符数据类型,是一种扩展的字符存储方式)
*		LP	(long pointer)
*		W	宽字节
*		STR	字符串
*/
void lpwstr()
{
	//需要包含下面两行,不然不能wcout字符串
	locale loc("chs");
	wcout.imbue( loc );

	//
	LPWSTR lps1 = L"直接赋值";
	wcout << lps1 << endl;

	//
	wchar_t* t1 = L"扩展字符串赋值";
	lps1 = t1;
	wcout << lps1 << endl;

	//
	LPWSTR lps2 = TEXT("宽字符转多字节");
	wcout << lps2 << " len=" << lstrlen(lps2) << endl;

	//convert from wchar_t* to char*
	int size = lstrlen(lps2)*2 + 1;
	char *t2 = new char[size];
	 //不加这句会乱码(多字节有多种,而宽字节只有unicode)
	setlocale(LC_ALL, "Chinese-simplified");
	wcstombs(t2, lps2, size); 
	cout << t2 << " len=" << strlen(t2) << endl;
	delete t2;

	//convert from char* to wchar_t*
	char *t3 = "多字节转宽字节";
	size = strlen(t3);
	wchar_t *t4 = new wchar_t[size];
	mbstowcs(t4, t3, size);
	wcout << t4 << endl;
	delete t4;
}

/**
*	LPSTR 与 char* 等价
*		LP	(long pointer)
*		STR	字符串
*/
void lpstr()
{
	LPSTR ls1 = "直接赋值";
	cout << ls1 << endl;

	char *t1 = "字符串赋值";
	LPSTR ls2 = t1;
	
	if(strcmp(ls2, t1) == 0)
	{
		char *t2 = ls2;
		cout << t2 << endl;
	}
}

/**
*	LPCSTR 与 const char* 等价
*		LP	(long pointer)
*		C	const
*		STR	字符串
*/
void lpcstr()
{
	LPCSTR ls1 = "直接赋值";
	cout << ls1 << endl;

	char *t1 = "字符串赋值";
	LPCSTR ls2 = t1;
	
	if(strcmp(ls2, t1) == 0)
	{
		const char *t2 = ls2;
		cout << t2 << endl;
	}
}

int main()
{	
	//char *
	lpstr();

	//wchar_t *
	lpwstr();

	return 0;
}
在是否定义了UNICODE宏下LPTSTR的含义又不同
#ifdef UNICODE
	typedef LPWSTR	PTSTR, LPTSTR;
	typedef LPCWSTR PCTSTR, LPCTSTR;
#else
	typedef LPSTR PTSTR, LPTSTR, PUTSTR, LPUTSTR;
	typedef LPCSTR PCTSTR, LPCTSTR, PCUTSTR, LPCUTSTR;
#endif

宽字节字符串有它自己的一系列字符串处理函数,和多字节字符串不一样,使用的时候要注意。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值