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();  


還有不少函數咱們會在之後的學習再給你們介紹。

相關文章
相關標籤/搜索