编程:编写一个截取字符串的函数,(网上流传的答案有的是错的)输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我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(01);   
  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.     }   
  41. }  

 

 

转自:http://longdechuanren.javaeye.com/blog/644792

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值