截取utf8字符串

string convertString(string str ,int length)  
{  
vector<std::string > subStrs;

int index=0;
int str_size=str.size();
int bytes=0;
while(index<str_size)
{
bytes=sub_utf_str(str,index,length);
if(bytes==-1)
{
return "wrong";
}

string substr=str.substr(index,bytes);
subStrs.push_back(substr);

index+=bytes;
}
    
    std::string resultStr;  
    for (unsigned int i = 0;i<subStrs.size();++i)  
    {  
        resultStr.append(subStrs[i]).append("\n");  
    } 
   
    return resultStr;  
}  


//从字符串str的index开始截取length个utf8字符,返回char的个数
int sub_utf_str(string str,int index,int length)
{
int i=0;
int count=0;
int str_size=str.size();
if(index>=str_size)
{
return -1;
}

for(i=0;i<length;i++)
{
char ch=str.at(index);
int bytes=utf8_check_first(ch);
if(bytes==0)
{
return -1;
}

index+=bytes;
count+=bytes;

if(index==str_size)
{
break;
}

if(index>str_size)
{
return -1;
}
}

return count;
}








int utf8_check_first(char byte)
{
    unsigned char u = (unsigned char)byte;

if(u&0x80==0)
{
return 1;
}

if(u&0x40==0)
{
return 0;
}

if(u&0x20==0)
{
return 2;
}


if(u&0x10==0)
{
return 3;
}

if(u&0x08==0)
{
return 4;
}

if(u&0x40==0)
{
return 5;
}


if(u&0x20==0)
{
return 6;
}

return 0;

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值