1. 程式人生 > >Java 按位元組擷取字串

Java 按位元組擷取字串




public class MyTest1 {

	@Test
	public void test() {
		String s = "112我似そして懂12非懂2";
		s = "てそしてててててそしてててて";
		try {
			System.out.println(substring(s,10));
			System.out.println(substring(s,7));
			System.out.println(substring(s,5));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 支援 GBK UTF-8 擷取
	 * @param orignal
	 * @param count
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String substring(String orignal, int count)   
            throws UnsupportedEncodingException {   
        if (orignal != null && !"".equals(orignal)) {   
            if (count > 0 && count < orignal.getBytes().length) {   
                StringBuffer buff = new StringBuffer();   
                char c;   
                for (int i = 0; i < count; i++) {   
                    c = orignal.charAt(i);   
                    buff.append(c);
                    count-=(charLength(c)-1);
                }   
                return buff.toString();   
            }   
        }   
        return orignal;   
    }   
	
	public static int charLength(char c){
		return String.valueOf(c).getBytes().length;
	}
}