cocos2d-x Utf8多语言编码类

//h
#pragma once
#include <string>
using namespace std;
class CMultiLang
{
public:
  static string iconvGbkToUtf8(const string& str);//Gbk是GB2312的扩展集多字节编码,可以包含繁体、日文假名等字符。
  //用法示例
  //CCLabelTTF* pLabel = CCLabelTTF::create(CMultiLang::iconvGbkToUtf8("わだぅわ、你好cocos2d-x!").c_str(), "Arial", TITLE_FONT_SIZE);
  //pLabel->setColor(ccc3(0, 255, 0));
  //字符编码转换函数
  static bool iconvConvert(const char* from_charset, const char* to_charset, const char* inbuf, int inlen, char* outbuf, int outlen);
};


//ccp
#include "MultiLang.h"
#include "iconv/iconv.h"
//字符编码转换函数
bool CMultiLang::iconvConvert(const char* from_charset, const char* to_charset, const char* inbuf, int inlen, char* outbuf, int outlen)
{
  iconv_t cd=iconv_open(to_charset, from_charset);
  if(cd==0)
    return false;
  const char** pin=&inbuf;
  char** pout=&outbuf;
  memset(outbuf, 0, outlen);
  size_t ret=iconv(cd, pin, (size_t*)&inlen, pout, (size_t*)&outlen);
  iconv_close(cd);
  return ret==(size_t)(-1)? false: true;
}
string CMultiLang::iconvGbkToUtf8(const string& str)
{
  const char* textIn=str.c_str();
  int inLen=str.length();
  int outLen=inLen*2+1;
  char* textOut=(char*)malloc(outLen);
    
  bool ret=false;
  if(textOut)
    ret=iconvConvert("gbk", "utf-8", textIn, inLen, textOut, outLen);
  string strOut=ret? string(textOut): string();
  free(textOut);
    
  return strOut;
}


你可能感兴趣的:(utf8)