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