Vc - Cocos2d中的字符串

使用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
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

莫忘输赢

莫忘输赢 - 收钱袋

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值