黑马程序员技术交流社区

标题: 按最大字节数取字符串,我这个算法太低效了,有谁能帮忙写个高效的呢 [打印本页]

作者: 向日葵的曙光    时间: 2014-4-10 17:39
标题: 按最大字节数取字符串,我这个算法太低效了,有谁能帮忙写个高效的呢
  1. package com.cg.test5;

  2. import java.io.IOException;
  3. public class Test {
  4.         public static void main(String[] args) throws IOException {
  5.                 String string="abc你好呀,我真的很想进黑马!Hello";
  6.                 int len=string.getBytes("utf-8").length;
  7.                 for(int x=0;x<len;x++){
  8.                         System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(string,x+1));
  9.                 }
  10.         }
  11.        
  12.         public static String cutStringByU8Byte(String str,int len) throws IOException{
  13.                 byte [] buf=str.getBytes("utf-8");
  14.                 int count=0;
  15.                 for(int x=len-1;x>=0;x--){
  16.                         if(buf[x]<0)
  17.                                 count++;
  18.                         else {
  19.                                 break;
  20.                         }
  21.                 }
  22.                 if(count%3==0)
  23.                         return new String(buf,0,len,"utf-8");
  24.                 else if(count%3==1)
  25.                         return new String(buf,0,len-1,"utf-8");
  26.                 else {
  27.                         return new String(buf,0,len-2,"utf-8");
  28.                 }
  29.         }
  30.        
  31. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2