下载此文档

关于字符串的小tips及多字节宽字符相互转换.docx


文档分类:IT计算机 | 页数:约7页 举报非法文档有奖
1/7
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/7 下载此文档
文档列表 文档介绍
char p[] = "hello";
CString str;
str.(Append)Format(L"%s", (CStringW)p);
多字节字符串与宽字符串的转换可使用C API者Win32 API.
C API: mbstowcs,wcstombs
Win32 API: MultiByteToWideChar, WideCharToMultiByte
 
下面着重介绍Win32 API的用法,C API的用法较为简单可参照Win32 API。
 
首先是WideCharToMultiByte
 
通常你需要配置4个参数(其他参数如是使用即可),红色标记的部分。
依次是源宽字符串,需要转换的长度(-1,则为转换整个字符串),目标多字节字符串,目标缓冲区长度。
返回值表示转换为目标多字节字符串实际需要的长度(包括结束符)。
所以通常需要调用WideCharToMultiByte两次:第一次产生目标缓冲区长度,第二次产生目标字符串,像下面这样
 
wchar_t* wcs = L"中国,你好!I Love You!";
int lengthOfMbs = WideCharToMultiByte( CP_ACP, 0, wcs, -1, NULL, 0, NULL, NULL);
char* mbs = new char[ lengthOfMbs ];
WideCharToMultiByte( CP_ACP, 0, wcs, -1, mbs, lengthOfMbs, NULL, NULL);
delete mbs;
mbs = NULL;
 
MultiByteToWideChar的用法类似
 
char* mbs = "中国,你好!I Love You!";
int lengthOfWcs = MultiByteToWideChar( CP_ACP, 0, mbs, -1, NULL, 0 );
wchar_t* wcs = new wchar_t[ lengthOfWcs ];
MultiByteToWideChar( CP_ACP, 0, mbs, -1, wcs, lengthOfWcs );
delete wcs;
wcs = NULL;
 
 
下面两个函数封装了转换过程
#include <>
#include <string>
 
std::string WcsToMbs( const std::wstring& wcs ) {
int lengthOfMbs = WideCharToMultiByte( CP_ACP, 0, (), -1, NULL, 0, NULL, NULL);
char* mbs = new char[ lengthOfMbs ];
WideCharToMultiByte( CP_ACP, 0, (), -1, mbs, lengthOfMbs, NULL, NULL);
std::string result = mbs;
delete mbs;
mbs = NULL;
return result;
}
 
std::wstring

关于字符串的小tips及多字节宽字符相互转换 来自淘豆网m.daumloan.com转载请标明出处.

非法内容举报中心
文档信息
  • 页数7
  • 收藏数0 收藏
  • 顶次数0
  • 上传人yunde113
  • 文件大小0 KB
  • 时间2014-07-24