黑马程序员技术交流社区
标题:
按最大字节数取字符串,我这个算法太低效了,有谁能帮忙写个高效的呢
[打印本页]
作者:
向日葵的曙光
时间:
2014-4-10 17:39
标题:
按最大字节数取字符串,我这个算法太低效了,有谁能帮忙写个高效的呢
package com.cg.test5;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String string="abc你好呀,我真的很想进黑马!Hello";
int len=string.getBytes("utf-8").length;
for(int x=0;x<len;x++){
System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(string,x+1));
}
}
public static String cutStringByU8Byte(String str,int len) throws IOException{
byte [] buf=str.getBytes("utf-8");
int count=0;
for(int x=len-1;x>=0;x--){
if(buf[x]<0)
count++;
else {
break;
}
}
if(count%3==0)
return new String(buf,0,len,"utf-8");
else if(count%3==1)
return new String(buf,0,len-1,"utf-8");
else {
return new String(buf,0,len-2,"utf-8");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2