Today, we prepare for the processing of the CSV file in the next section and start to define a class for separating strings by specific symbols. The implementation is as follows:
Class StringUtil: public CCObject {public: static StringUtil * sharedStrUtil (); bool init ();/*** splits the string using a separator and stores the result in a list, the objects in the list are CCString */CCArray * split (const char * srcStr, const char * sSep); private: static StringUtil * mStringUtil;}; # endif
# Include "StringUtil. h "StringUtil * StringUtil: mStringUtil = NULL; StringUtil * StringUtil: sharedStrUtil () {if (mStringUtil = NULL) {mStringUtil = new StringUtil (); if (mStringUtil & mStringUtil-> init () {mStringUtil-> autorelease () ;}else {reverse (mStringUtil); mStringUtil = NULL ;}} return mStringUtil ;} bool StringUtil: init () {return true;} CCArray * StringUtil: split (const char * srcStr, Const char * sSep) {CCArray * stringList = CCArray: create (); int size = strlen (srcStr ); /* convert data to a Cocos2d-x String object */CCString * str = CCString: create (srcStr); int startIndex = 0; int endIndex = 0; endIndex = str-> m_sString.find (sSep); CCString * spliStr = NULL;/* split the string based on the separator and add it to the list */while (endIndex> 0) {spliStr = CCString: create ("");/* intercept string */spliStr-> m_sString = str-> m_sString.substr (startI Ndex, endIndex);/* Add a string to the list */stringList-> addObject (spliStr ); /* extract the remaining string */str-> m_sString = str-> m_sString.substr (endIndex + 1, size ); /* Find the subscript of the next separator */endIndex = str-> m_sString.find (sSep );} /* Add the remaining strings to the list */if (str-> m_sString.compare ("")! = 0) {stringList-> addObject (CCString: create (str-> m_sString) ;}return stringList ;}Add debugging in HelloWorld:
bool HelloWorld::init(){ bool bRet = false; do { CCArray *strlist = StringUtil::sharedStrUtil()->split("Zhangxl,aihaoguangfan,basketball,swim",","); CCObject *object = NULL; CCARRAY_FOREACH(strlist,object) { CCString *str = (CCString*)object; CCLOG(str->getCString()); } bRet = true; } while (0); return bRet;}The running effect is as follows: