[Java] 按字节截取混有中文汉字的字符串 中英文字符串截取 →→→→→进入此内容的聊天室

来自 , 2020-07-18, 写在 Java, 查看 117 次.
URL http://www.code666.cn/view/e7f8a7fb
  1. import java.io.UnsupportedEncodingException;  
  2.  
  3. public class CutString {  
  4.  
  5.     /**  
  6.      * 判断是否是一个中文汉字  
  7.      *  
  8.      * @param c  
  9.      *            字符  
  10.      * @return true表示是中文汉字,false表示是英文字母  
  11.      * @throws UnsupportedEncodingException  
  12.      *             使用了JAVA不支持的编码格式  
  13.      */  
  14.     public static boolean isChineseChar(char c)  
  15.             throws UnsupportedEncodingException {  
  16.         // 如果字节数大于1,是汉字  
  17.         // 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了  
  18.         return String.valueOf(c).getBytes("GBK").length > 1;  
  19.     }  
  20.  
  21.     /**  
  22.      * 按字节截取字符串  
  23.      *  
  24.      * @param orignal  
  25.      *            原始字符串  
  26.      * @param count  
  27.      *            截取位数  
  28.      * @return 截取后的字符串  
  29.      * @throws UnsupportedEncodingException  
  30.      *             使用了JAVA不支持的编码格式  
  31.      */  
  32.     public static String substring(String orignal, int count)  
  33.             throws UnsupportedEncodingException {  
  34.         // 原始字符不为null,也不是空字符串  
  35.         if (orignal != null && !"".equals(orignal)) {  
  36.             // 将原始字符串转换为GBK编码格式  
  37.             orignal = new String(orignal.getBytes(), "GBK");  
  38.             // 要截取的字节数大于0,且小于原始字符串的字节数  
  39.             if (count > 0 && count < orignal.getBytes("GBK").length) {  
  40.                 StringBuffer buff = new StringBuffer();  
  41.                 char c;  
  42.                 for (int i = 0; i < count; i++) {  
  43.                     // charAt(int index)也是按照字符来分解字符串的  
  44.                     c = orignal.charAt(i);  
  45.                     buff.append(c);  
  46.                     if (CutString.isChineseChar(c)) {  
  47.                         // 遇到中文汉字,截取字节总数减1  
  48.                         --count;  
  49.                     }  
  50.                 }  
  51.                 return buff.toString();  
  52.             }  
  53.         }  
  54.         return orignal;  
  55.     }  
  56.  
  57.     public static void main(String[] args) {  
  58.         // 原始字符串  
  59.         String s = "我ZWR爱JAVA";  
  60.         System.out.println("原始字符串:" + s);  
  61.         try {  
  62.             System.out.println("截取前1位:" + CutString.substring(s, 1));  
  63.             System.out.println("截取前2位:" + CutString.substring(s, 2));  
  64.             System.out.println("截取前4位:" + CutString.substring(s, 4));  
  65.             System.out.println("截取前6位:" + CutString.substring(s, 6));  
  66.         } catch (UnsupportedEncodingException e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70. }  

回复 "按字节截取混有中文汉字的字符串 中英文字符串截取"

这儿你可以回复上面这条便签

captcha