zoukankan      html  css  js  c++  java
  • Java 字符串截取问题

    编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我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.     }   
    逼着你往前走的,不是前方梦想的微弱光芒,而是身后现实的万丈深渊。 ---------致自己
  • 相关阅读:
    hive mind ioc retired already
    存储系统介绍
    最后找到有源码的ORM
    DEDE在图集列表中调出图集的所有图片[首页也适用]
    客户端接收发邮件时,出现“无法连接到服务器
    4种常用扒站工具(webzip、ha_TeleportPro、Offline Explorer、wget)
    CSS3 backgroundsize图片自适应
    webzip怎么用 如何用webzip下载整个网站?
    ArrayList Vector LinkedList 区别与用法
    wish list: 考虑使用nutch给自己的博客做一个全文检索
  • 原文地址:https://www.cnblogs.com/Fairy-02-11/p/6203034.html
Copyright © 2011-2022 走看看