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

Java按位元組數擷取字串

1、擷取字串,若是遇到不完整的中文,則捨棄掉那部分中文資訊

碰到可能會擷取漢字的情況,當然是要不能截取出亂碼來,就是不能對整個漢字擷取一半。如"我ABC漢字d"這個字串,擷取5個位元組的時候,應該是"我ABC",而擷取8個位元組的時候,應該是"我ABC漢",而不應該是"我ABC漢?",其中"?"為半個漢字,可理解為向前擷取

package com.lxh.ser.test;

import java.io.UnsupportedEncodingException;

public class SubStrTest {
	
	private static final String DEFAULT_ENCODING = "GBK";
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "我ABC漢字d";
		for (int i = 0; i < str.getBytes(DEFAULT_ENCODING).length; i++) {
			System.out.println("i: " + i + "  " + subStr(str, i));
		}
	}

	/**
	 * @param str 需要擷取的字串
	 * @param subSLength 需要擷取的位元組數
	 * @return 擷取完成的字串
	 * @throws UnsupportedEncodingException
	 */
	public static String subStr(String str, int subStrLength) throws UnsupportedEncodingException {
		if (null == str) {
			return "";
		}
		// 擷取位元組數
		int tempSubLength = subStrLength;
		// 擷取的子串
		String subStr = str.substring(0, str.length() < subStrLength ? str.length() : subStrLength);
		// 擷取子串的位元組長度
		int subStrByetsL = subStr.getBytes(DEFAULT_ENCODING).length;
		// 比較擷取後的字串位元組數大於需要擷取的自己數,說明擷取的字串中包含有漢字並且擷取後的位元組數大於需要的位元組數
		while (subStrByetsL > tempSubLength) {
			int subSLengthTemp = --subStrLength;
			// 再少擷取一個字元
			subStr = str.substring(0, subSLengthTemp > str.length() ? str.length() : subSLengthTemp);
			subStrByetsL = subStr.getBytes(DEFAULT_ENCODING).length;
		}
		return subStr;
	}
}