Cocos2d-x中的字符串

Cocos2d-x中可以使用的字符串constchar*std::stringcocos2d::__String等,其中const char*C风格的字符串,std::stringC++风格的字符串,它封装了const char*cocos2d::__String才是Cocos2d-x引擎提供的字符串类,这些字符串均可以互相转换,它们会在不一样的场景下使用,具体使用那个能够看具体的API

使用const char*std::string

咱们在C++中两种类型均可以使用,可是std::string是一个类,具体面向对象的优势,而const char*没有。咱们是下面代码初始化std::string对象。html

        

[html] view plaincopy在CODE上查看代码片派生到个人代码片iphone

  1. std::string name = "tony";  函数

  2. td::string name = std::string("tony");  学习


咱们不须要使用指针,也不须要关心内存释放问题,在做用域超出以后std::string对象别释放。咱们能够经过下面的语句把std::string转化为const char*类型。编码

[html] view plaincopy在CODE上查看代码片派生到个人代码片spa

  1. const char* cstring = name.c_str();  .net


咱们可使用std::string指针类型,可是要配合使用new关键字开辟内存空间,而后再也不使用的时候要经过delete释放内存。设计

[html] view plaincopy在CODE上查看代码片派生到个人代码片指针

  1. std::string* name =newstd::string("tony");  code

  2. … …  

  3. delete name;  


使用std::string指针对象时候,咱们能够经过下面的代码转化为const char*类型。

   

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. const char* cstring = name->c_str();  


const char* std::string的在Cocos2d-x中还有不少,咱们会在后面的学习中给你们介绍。

使用cocos2d::__String

cocos2d::__StringCocos2d-x经过的一个字符串类,它的设计模拟了Objective-CNSString类,这因为Cocos2d-x源自于Cocos2d-iphone,cocos2d::__String也是基于Unicode双字节编码。

cocos2d::__String的类图以下图所示,


建立它的主要的静态create函数以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. static__String * create (const std::string &str)  

  2. static__String * createWithFormat (const char *format,...)  


使用create函数的实例代码以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. __String* name=  __String::create("Hi,Tony");  

  2. int num=123;  

  3. __String* ns = __String::createWithFormat("%d",num);  

  4.    


cocos2d::__String还提供了一些数据类型之间的转换函数。例如:cocos2d::__String转换为const char*类型,这种转换用的比较多的,示例代码以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. __String* name=  __String::create("Hi,Tony");  

  2. const char *cstring=name->getCString();  


const char*转换为cocos2d::__String类型,示例代码以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. const char* cstring = "Hi,Tony";  

  2. __String*ns=__String::createWithFormat("%s",cstring);  


std::string转换为cocos2d::__String类型,示例代码以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. std::string string = "Hi,Tony";     

  2. __String*ns=__String::createWithFormat("%s",string.c_str());  


cocos2d::__String转换为int类型,示例代码以下:

[html] view plaincopy在CODE上查看代码片派生到个人代码片

  1. int num = 123;  

  2. __String* ns =__String::createWithFormat("%d",num);  

  3. int num2 = ns->intValue();  


还有不少函数咱们会在之后的学习再给你们介绍。

相关文章
相关标签/搜索