Java String abbreviate GBK String

Description

Java String abbreviate GBK String


//package com.demo2s;

import java.io.UnsupportedEncodingException;

public class Main {


    public static String abbreviateGBKString(String str, int len) {
        if (str == null || len == 0) {
            return "";
        }/*from  www  .  j a v a 2 s.c o m*/
        try {
            byte[] strByte = str.getBytes("GBK");
            if (strByte.length <= len) {
                return str;
            }
            byte[] rtByte = new byte[len];
            System.arraycopy(strByte, 0, rtByte, 0, len);
            boolean truncated = false;
            for (int i = 0; i < len; i++) {
                int value = (int) strByte[i];
                if (value < 0) {
                    if (i == len - 1) {
                        truncated = true;
                        break;
                    } else {
                        i++;
                    }

                }
            }
            if (truncated) {
                len = (len == 1) ? len + 1 : len - 1;
            }
            return new String(strByte, 0, len, "GBK") + "...";
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }
}



PreviousNext

Related