Search code examples
cocos2d-x

How to Replace a CCString?


Is there anything similar to a string Replace method for CCString? something like that takes another 2 CCString parameters, switching the first with the second


Solution

  • No, you need to implement it yourself like the following.

    #include <string>
    
    using std::string;
    
    CCString* replaceCCString(CCString* cs, const CCString* csearch, const CCString* creplace)
    {
        string s = cs->getCString();
        string search = csearch->getCString();
        string replace = creplace->getCString();
    
        for (size_t pos = 0; ; pos += replace.length()) {
            pos = s.find(search, pos);
            if (pos == string::npos)
                break;
    
            s.erase(pos, search.length());
            s.insert(pos, replace);
        }
    
        return CCString::create(s);
    }