cocos2d-x 字符串截取

A.h

private: 
    static std::vector<std::string> parseUTF8(const std::string &str);
public:
    static std::string subUTF8(const std::string &str, int from, int to);

A.cpp

std::vector<std::string> A::parseUTF8(const std::string &str)
{
    int l = str.length();
    std::vector<std::string> ret;
    ret.clear();
    for(int p = 0; p < l; ) 
    {
        int size=0;
        unsigned char c = str[p];
        if(c < 0x80) {
            size = 1;
        }
        else if(c < 0xc2) 
        {
            size = 2;
        } 
        else if(c < 0xe0)
        {
            size = 2;
        } 
        else if(c < 0xf0)
        {
            size = 3;
        } 
        else if(c < 0xf8) 
        {
            size = 4;
        } 
        else if (c < 0xfc) 
        {
            size = 5;
        } 
        else if (c < 0xfe)
        {
            size = 6;
        }
        else
            size = 7;
        std::string temp = "";
        temp = str.substr(p, size);
        ret.push_back(temp);
        p += size;
    }
    return ret;
}

std::string A::subUTF8(const std::string &str,int from, int to)
{
    if(from > to) return "";
 
    if (str.length() < to) return "";

    std::vector<std::string> vstr = parseUTF8(str);
 
    std::vector<std::string>::iterator iter=vstr.begin();
    std::string res;
    std::string result;
    for(iter=(vstr.begin() + from); iter != (vstr.begin() + to); iter++)
    {
        res += *iter;
    }
    return res;
}

 

posted @ 2014-11-14 11:30  猿走天下  阅读(2438)  评论(0编辑  收藏  举报