Fairy
逼着你往前走的,不是前方梦想的微弱光芒,而是身后现实的万丈深渊。 ---------致自己

编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4

Java代码 
  1. public class StringSplit {   
  2.     public static void main(String[] args) throws Exception {   
  3.         String ss = "a很bc你好";   
  4.         System.out.println(splitString(ss, 1));   
  5.     }   
  6.   
  7.     public static String splitString(String str, int byteLength)   
  8.             throws Exception {   
  9.         //如果字符串为空,直接返回   
  10.         if(str == null || "".equals(str)) {   
  11.             return str;   
  12.         }   
  13.         //用于统计这个字符串中有几个中文字符   
  14.         int wordCount = 0;   
  15.         //统一按照gbk编码来得到他的字节数组,因为不同的编码字节数组是不一样的。   
  16.         byte[] strBytes = str.getBytes("GBK");   
  17.            
  18.         //如果只截取一位,而且第一位是中文字符时的处理   
  19.         if (byteLength == 1) {   
  20.             if (strBytes[0] < 0) {   
  21.                 return str.substring(0, 1);   
  22.             }   
  23.         }   
  24.         //字符串中的一个中文会使得wordCount 加两次   
  25. //如果你这个字节取出来的是一个汉字也就是两个字节当中的一个的话val的值为负数   
  26.         for (int i = 0; i < byteLength; i++) {   
  27.             int val = strBytes[i];   
  28.             if (val < 0) {   
  29.                 wordCount++;   
  30.             }   
  31.         }   
  32.            
  33.         //如果传递的这个截取的位数没有截到半个中文上面,那么就按照byteLength - (wordCount / 2个长度进行截取   
  34.         if (wordCount % 2 == 0) {   
  35.             return str.substring(0, (byteLength - (wordCount / 2)));   
  36.         }   
  37.         //否则,我们就舍弃多出来的这一位 所以  -1    
  38.         return str.substring(0, (byteLength - (wordCount / 2) - 1));   
  39.   
  40.     }   
posted on 2016-12-20 16:03  Fairy-02  阅读(777)  评论(0编辑  收藏  举报