使用const char* 和std::string 和 cocos2d::_String等,其中,const char* 是c风格的字符串,std::string是C++风格的字符串,cocos2d::_String才是Cocos提供的字符串类,这些字符串可以相互转换。
//初始化std::string对象
std::string name = "tom";
std::string name = std::string("tom");
//使用下列方式将std::string转化为const char*
const char *cstring = name.c_str();
//new使用
std::string *name = new std::string("tom");
//delete使用
delete name;
//使用cocos2d::_String
//创建的静态函数
static _String *create(const std::string &str);
static _String *createWithFormate(const char* format,……)
//使用_String
_String *name = _String::create("tom");
int num = 123;
_String *ns = _String::CreateWithFormat("%d",num);
//_String中用于类型转换函数
//_String to const char*
_String *name = _String::Create("tom");
const char* cstring = name->getCstring();
//std::string to _String
std::string string = "tom";
_String *ns = _String::create%d",string.c_str());
//_String to int
int num1 = 123;
_String *ns = _String::createWithFormat("%d",num1);
int num2 = ns->toValue();
//gbk to utf8
string gbk_to_utf8(const string text)
{
#if (CC_TRAGET_PLATFORM == CC_PLATFORM_WIN32)
//采用lambda表达式 将string转换为wstring
wstring tes = [=](){
setlocale(LC_ALL,"chs");
const char *source = text.c_str();
size_t _DSize = text.size()+1;
wchrar_t *_Dest = new wchar_t[_DSize];
wmemset(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete[] _Dest;
setlocale(LC_ALL,"C");
return result;
}();
int asciSize = WideCharTbMultiByte(CP_UTF8,0,tes.size(),NULL,0,NULL,NULL);
if(asciSize == ERROR_NO_UNICODE_TRANSLATION || asciSize == 0)
{
return string();
}
char *resultString = new char[asciSize];
int converResult = WideCharToMultiByte(CP_UTF8,0,tes.c_str(),tes.size(),
resultString,acciSize,NULL,NULL);
if(conveResult != asciSize)
{
return string();
}
string buffer = "";
buffer.append(resultString,asciSize);
delete[] resultString;
return buffer;
#else
return buffer;
#endif
}