zoukankan      html  css  js  c++  java
  • 给定一个字符串,包含中文字符和英文字符,取给定大小字节的子串。

     题目如下:给定一个字符串,包含中文字符和英文字符,取给定大小字节的子串。


         代码如下:

    1. import java.io.UnsupportedEncodingException;  
    2.   
    3.   
    4. public class CutString {  
    5.     /** 
    6.      * 判断是否是一个中文汉字 
    7.      * @param c 
    8.      * @return true表示是中文汉字,false表示是英文字符 
    9.      * @throws UnsupportedEncodingException 
    10.      */  
    11.     public static boolean isChineseChar(char c) throws UnsupportedEncodingException {  
    12.           
    13.         return String.valueOf(c).getBytes("GBK").length > 1;  
    14.     }  
    15.       
    16.     /** 
    17.      * 按照字节位数截取字符串 
    18.      * @param original 
    19.      * @param count 要截取的字符串的字节位数 
    20.      * @return 
    21.      * @throws UnsupportedEncodingException 
    22.      */  
    23.     public static String subString(String original, int count) throws UnsupportedEncodingException {  
    24.         if(null!=original && !"".equals(original)) {  
    25.             original = new String (original.getBytes(), "GBK");  
    26.             if(count>0 && count<original.getBytes().length) {  
    27.                 StringBuffer buff = new StringBuffer();  
    28.                 char c;  
    29.                 for(int i=0; i<count; i++) {  
    30.                     c = original.charAt(i);  
    31.                     buff.append(c);  
    32.                     if(CutString.isChineseChar(c)) {  
    33.                         //一个中文字符两个字节,所以对于一个字符串,遇到一个中文字符,顶两个字节。  
    34.                         --count;  
    35.                     }  
    36.                 }  
    37.                 return buff.toString();  
    38.             }  
    39.         }  
    40.         return original;  
    41.     }  
    42.       
    43.     public static void main(String[] args) {  
    44.         String s = "我zwr爱Java";  
    45.         System.out.println("原始字符串:" + s);  
    46.         try {  
    47.             System.out.println("截取1位" + CutString.subString(s, 1));  
    48.             System.out.println("截取2位" + CutString.subString(s, 2));  
    49.             System.out.println("截取3位" + CutString.subString(s, 3));  
    50.             System.out.println("截取4位" + CutString.subString(s, 4));  
    51.             System.out.println("截取6位" + CutString.subString(s, 6));  
    52.         } catch (UnsupportedEncodingException e) {  
    53.             e.printStackTrace();  
    54.         }  
    55.     }  
    56.   
    57. }  
  • 相关阅读:
    Docker学习总结(四)--应用部署
    strcat的由来
    ubuntu man不到pthread_mutex_XX
    string::front
    string::find_last_of
    string::find_last_not_of
    string::find_first_of
    string::find_first_not_of
    string::erase
    string::empty
  • 原文地址:https://www.cnblogs.com/allenzhaox/p/3201791.html
Copyright © 2011-2022 走看看