- import java.io.UnsupportedEncodingException;
- import java.nio.charset.Charset;
- public class StringUtils {
- public static String truncate(String s, int n, String encodeName) throws UnsupportedEncodingException {
- if (s == null || s.isEmpty()) {
- throw new NullPointerException("StringUtils: truncate(String s, int n), 參數s不能爲空!");
- }
- if (n <= 0) {
- throw new ArrayIndexOutOfBoundsException("StringUtils: truncate(String s, int n), 參數n不能爲負數!");
- }
- if (n > s.getBytes(encodeName).length) {
- n = s.getBytes(encodeName).length;
- }
- byte[] resultBytes = new byte[n];
- int j = 0;
- for (int i = 0; i < s.length(); i++) {
- byte[] bytes = String.valueOf(s.charAt(i)).getBytes(encodeName);
- if (bytes.length <= n - j) {
- for (int k = 0; k < bytes.length; k++) {
- resultBytes[j] = bytes[k];
- j++;
- }
- } else {
- break;
- }
- }
- return new String(resultBytes, 0, j, encodeName);
- }
- public static String truncate(String s, int n) throws UnsupportedEncodingException {
- return truncate(s, n, Charset.defaultCharset().toString());
- }
- public static void main(String[] args) {
- String s = "Hello: 你好; World: 世界.";
- String encodeName = "GBK";
- try {
- for (int i = 1; i <= s.getBytes(encodeName).length; i++) {
- System.out.println(i + ": " + StringUtils.truncate(s, i, encodeName) + "*");
- }
- } catch (UnsupportedEncodingException unsupportedEncodingException) {
- }
- }
- // Output:
- // 1: H*
- // 2: He*
- // 3: Hel*
- // 4: Hell*
- // 5: Hello*
- // 6: Hello:*
- // 7: Hello: *
- // 8: Hello: *
- // 9: Hello: 你*
- // 10: Hello: 你*
- // 11: Hello: 你好*
- // 12: Hello: 你好;*
- // 13: Hello: 你好; *
- // 14: Hello: 你好; W*
- // 15: Hello: 你好; Wo*
- // 16: Hello: 你好; Wor*
- // 17: Hello: 你好; Worl*
- // 18: Hello: 你好; World*
- // 19: Hello: 你好; World:*
- // 20: Hello: 你好; World: *
- // 21: Hello: 你好; World: *
- // 22: Hello: 你好; World: 世*
- // 23: Hello: 你好; World: 世*
- // 24: Hello: 你好; World: 世界*
- // 25: Hello: 你好; World: 世界.*
- }