关于字符长度的运算问题

 std::string textStr = element.text;
    std::string lines;
    int len = 40;
    if(element.text.length() > len){
        for(int cur = 0; cur < len;){
            char t = textStr[cur];
            if((t&0xE0) == 0xE0){    //3byte
                lines = lines + t + textStr[cur+1] + textStr[cur+2];
                cur += 3;
            }else if((t & 0xC0) == 0xC0){//2byte
                lines = lines + t + textStr[cur+1];
                cur += 2;
            }else { //1byte
                lines = lines + t;
                cur += 1;
            }
        }
        textStr = lines + ”“;

        CCLog(“streaming text:%s”, lines.c_str());




///////////////////////////

方法二

#pragma mark 字符串换行重组

std::string lineFeeds(const std::string &str, int iCurrentIndex) {

    if (typeid(str) == typeid(std::string) && str.length() > 0 &&iCurrentIndex > 0) {

        std::stringstream result;

        std::vector<<span class="s2">std::string> temp;

        temp = parseUTF8(str); 

        int iStringLength = temp.size();

        for (int i = 0;i < iStringLength;i++) {

            result<<temp[i];

            if (iCurrentIndex == i)

                result<<"\n";

        }

        return result.str();

    } else {

        return "";

    }

}


#pragma mark UTF8字符解析

std::vector<<span class="s2">std::string>  parseUTF8(const std::string &str) {

    int l = str.length();

    std::vector<</span>std::string> ret;

    ret.clear();

    for(int p = 0; p < l; ) {

        int size;

        unsigned char c = str[p];

        if(c < 0x80) {

            size = 1;

        } else if(c < 0xc2) {

        } 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;

        }

        std::string temp = "";

        temp = str.substr(p, size);

        ret.push_back(temp);

        p += size;

    }

    return ret;

}

#pragma mark 截取UTF8字符串

std::string subUTF8(const std::string &str,int from, int to)

{

    if(from > to) return "";

    vector<<span class="s2">std::string> test = parseUTF8(str);

    if (test.size() < to) return str;

    vector<<span class="s2">string>::iterator iter = test.begin();

    std::string res;

    std::string result;

    for(iter=(test.begin() + from); iter != (test.begin() + to); iter++)

    {

        res += *iter;

        

    }

    return res;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值