Get substring for GBK String - Java java.lang

Java examples for java.lang:String Substring

Description

Get substring for GBK String

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) {
        String origin = "java2s.com";
        int len = 2;
        System.out.println(substring(origin, len));
    }//from  ww w.  j a v a  2  s .c o  m

    public static String substring(String origin, int len) {
        if (origin == null || origin.equals("") || len < 1) {
            return "";
        }
        byte[] strByte = new byte[len];
        if (len > getRealLength(origin)) {
            return origin;
        }
        try {
            System.arraycopy(origin.getBytes("GBK"), 0, strByte, 0, len);
            int count = 0;
            for (int i = 0; i < len; i++) {
                int value = (int) strByte[i];
                if (value < 0) {
                    count++;
                }
            }
            if (count % 2 != 0) {
                len = (len == 1) ? ++len : --len;
            }
            return new String(strByte, 0, len, "GBK");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static int getRealLength(String str) {
        try {
            return str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
            return -1;
        }
    }
}

Related Tutorials