Java中按字節數截取字符串



  1. import java.io.UnsupportedEncodingException; 
  2. import java.nio.charset.Charset; 
  3.  
  4. public class StringUtils { 
  5.     public static String truncate(String s, int n, String encodeName) throws UnsupportedEncodingException { 
  6.         if (s == null || s.isEmpty()) { 
  7.             throw new NullPointerException("StringUtils: truncate(String s, int n), 參數s不能爲空!"); 
  8.         } 
  9.         if (n <= 0) { 
  10.             throw new ArrayIndexOutOfBoundsException("StringUtils: truncate(String s, int n), 參數n不能爲負數!"); 
  11.         } 
  12.         if (n > s.getBytes(encodeName).length) { 
  13.             n = s.getBytes(encodeName).length; 
  14.         } 
  15.         byte[] resultBytes = new byte[n]; 
  16.         int j = 0
  17.         for (int i = 0; i < s.length(); i++) { 
  18.             byte[] bytes = String.valueOf(s.charAt(i)).getBytes(encodeName); 
  19.             if (bytes.length <= n - j) { 
  20.                 for (int k = 0; k < bytes.length; k++) { 
  21.                     resultBytes[j] = bytes[k]; 
  22.                     j++; 
  23.                 } 
  24.             } else { 
  25.                 break
  26.             } 
  27.         } 
  28.         return new String(resultBytes, 0, j, encodeName); 
  29.     } 
  30.      
  31.     public static String truncate(String s, int n) throws UnsupportedEncodingException { 
  32.         return truncate(s, n, Charset.defaultCharset().toString()); 
  33.     } 
  34.      
  35.     public static void main(String[] args) { 
  36.         String s = "Hello: 你好; World: 世界."
  37.         String encodeName = "GBK"
  38.         try { 
  39.             for (int i = 1; i <= s.getBytes(encodeName).length; i++) { 
  40.                 System.out.println(i + ": " + StringUtils.truncate(s, i, encodeName) + "*"); 
  41.             } 
  42.         } catch (UnsupportedEncodingException unsupportedEncodingException) { 
  43.         } 
  44.     } 
  45.      
  46. //    Output: 
  47. //    1: H* 
  48. //    2: He* 
  49. //    3: Hel* 
  50. //    4: Hell* 
  51. //    5: Hello* 
  52. //    6: Hello:* 
  53. //    7: Hello: * 
  54. //    8: Hello: * 
  55. //    9: Hello: 你* 
  56. //    10: Hello: 你* 
  57. //    11: Hello: 你好* 
  58. //    12: Hello: 你好;* 
  59. //    13: Hello: 你好; * 
  60. //    14: Hello: 你好; W* 
  61. //    15: Hello: 你好; Wo* 
  62. //    16: Hello: 你好; Wor* 
  63. //    17: Hello: 你好; Worl* 
  64. //    18: Hello: 你好; World* 
  65. //    19: Hello: 你好; World:* 
  66. //    20: Hello: 你好; World: * 
  67. //    21: Hello: 你好; World: * 
  68. //    22: Hello: 你好; World: 世* 
  69. //    23: Hello: 你好; World: 世* 
  70. //    24: Hello: 你好; World: 世界* 
  71. //    25: Hello: 你好; World: 世界.* 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章