- 论坛徽章:
- 0
|
unix下的汉字处理问题
如何把一个汉字作为一个字符来处理?在以前,似乎比较麻烦,因为一个汉字一向是由2个字符来表示的。比较汉字,往往变成了字符串的比较。
unicode出现之后,情况就好多了,每个汉字都有唯一的编码,从此汉字就可以作为单个字符来对待了。
stl提供了string类来处理字符串,但是针对的是单字节字符串。如果想处理汉字,可以选择wstring。用法和string完全相同,但是处理的是宽字符。
string到wstring之间的转换,似乎stl没有提供好的方法,所以还得用c的库函数来处理。
以下给出一段代码,演示在unix下面,处理汉字的方法
/*
FileName: str2wstrdemo.cpp
Compile command:aCC -AA +DD64 -I/opt/aCC/include_std str2wstrdemo.cpp -lstd_v2 -lCsup_v2 -o 1
*/
#include
#include
#include
#include
#include
namespace std {} using namespace std;
int main()
{
int cnt;
wchar_t wcs[100], wc;
string myword="列表内容为:";
setlocale(LC_CTYPE, ""); //很重要,没有这一句,转换会失败
mbstowcs(wcs, myword.c_str(), 99);
wstring newword(wcs);
cout<<"string content is:"<<myword.c_str()<< endl;
cout<<"wstring size is:" <<newword.size()<<endl;
return 0;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4353/showart_20025.html |
|