天天看點

unix下的漢字處理問題

  如何把一個漢字作為一個字元來處理?在以前,似乎比較麻煩,因為一個漢字一向是由2個字元來表示的。比較漢字,往往變成了字元串的比較。unicode出現之後,情況就好多了,每個漢字都有唯一的編碼,從此漢字就可以作為單個字元來對待了。

  stl提供了string類來處理字元串,但是針對的是單位元組字元串。如果想處理漢字,可以選擇wstring。用法和string完全相同,但是處理的是寬字元。string到wstring之間的轉換,似乎stl沒有提供好的方法,是以還得用c的庫函數來處理。

以下給出一段代碼,示範在unix下面,處理漢字的方法

unix下的漢字處理問題

#include  < iostream >

unix下的漢字處理問題

#include  < string >

unix下的漢字處理問題

#include  < list >

unix下的漢字處理問題

#include  < stdlib.h >

unix下的漢字處理問題

#include  < locale.h >  

unix下的漢字處理問題
unix下的漢字處理問題

namespace  std  ... {}   using   namespace  std;

unix下的漢字處理問題
unix下的漢字處理問題

int  main()

unix下的漢字處理問題
unix下的漢字處理問題

... {

unix下的漢字處理問題

  int cnt;

unix下的漢字處理問題

  wchar_t wcs[100], wc;

unix下的漢字處理問題
unix下的漢字處理問題

  string myword="清單内容為:";

unix下的漢字處理問題
unix下的漢字處理問題

  setlocale(LC_CTYPE, "");  //很重要,沒有這一句,轉換會失敗

unix下的漢字處理問題
unix下的漢字處理問題

  mbstowcs(wcs, myword.c_str(), 99);

unix下的漢字處理問題
unix下的漢字處理問題

  wstring newword(wcs);

unix下的漢字處理問題
unix下的漢字處理問題

  cout<<"string content is:"<<myword.c_str()<< endl; 

unix下的漢字處理問題
unix下的漢字處理問題

  cout<<"wstring size is:"  <<newword.size()<<endl;

unix下的漢字處理問題
unix下的漢字處理問題
unix下的漢字處理問題

  return 0;

unix下的漢字處理問題

}

unix下的漢字處理問題