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

java按位元組擷取字串

首先分編碼格式,gbk和gb2312公用一套方案,,而u8是另一套。

為什麼呢,因為gbk和gb2312是兩個位元組表示一個漢字,前者兩個位元組的值都是負數,後者第二個數有時為正,比如(琲bei)

那u8呢,是三個位元組表示一個漢字,所以判斷條件比gbk多了一點。

不多說,看程式-----

package 按位元組擷取字串;

import java.io.IOException;

/**
 * 以u8編碼講解按位元組擷取字串
 * 
 * @author nice
 *
 */
public class DemoUtf {

	public static void main(String[] args) throws IOException {
		// 定義一個字串
		String str = "asd我是高手wuha高手hhh";
		// 求字串得長度
		int len = str.getBytes("utf-8").length;
		// 迴圈列印所有在字串長度範圍內的取值輸出結果
		for (int i = 0; i < len; i++) {
			System.out.println("按" + (i + 1) + "位元組擷取:" + currentString(str, i + 1));
		}
	}

	private static String currentString(String str, int len) throws IOException {

		// 先把字串轉換為字元陣列
		byte[] b = str.getBytes("utf-8");

		// 定義一個計數器
		int count = 0;

		// 從最後一個位元組開始做判斷
		for (int i = len - 1; i >= 0; i--) {
			if (b[i] < 0)
				count++;
			else
				break;
		}

		// 在for迴圈裡面判斷完後,根據u8編碼三個位元組組成一個漢字的特點,可以推出指定位元組對應是不是一個完整的漢字,
		// 不是就返回到字串長度減去這個不完整的位元組數

		// 是3的倍數,那就是一個完整的漢字
		if (count % 3 == 0)
			return new String(b, 0, len, "utf-8");

		// 是漢字前面的哪個位元組,就減去一個個位元組
		else if (count % 3 == 1)
			return new String(b, 0, len - 1, "utf-8");

		// 是漢字中間的哪個位元組,就減去兩個位元組
		else
			return new String(b, 0, len - 2, "utf-8");

	}
}
package 按位元組擷取字串;

import java.io.IOException;

/**
 * 以gbk編碼講解。gb2312可能略有不同,前者是兩個負數,後者第二個有時是正數,比如這個琲(bei) u8的話,他是用三個位元組表示的。
 * 比較法和gbk類似(取餘判斷多了一些)
 * 
 * @author nice
 *
 */
public class Demo {

	public static void main(String[] args) throws IOException {

		String str = "ab琲琲cd琲琲";
		// String str = "ab你好cd謝謝";
		int len = str.getBytes("GBK").length;

		for (int i = 0; i < len; i++) {
			System.out.println("擷取" + (i + 1) + "個位元組的結果是" + outStringByByte(str, i + 1));
		}

	}

	private static String outStringByByte(String str, int len) throws IOException {

		byte[] btf = str.getBytes("gbk");
		int count = 0;

		for (int j = len - 1; j >= 0; j--) {
			if (btf[j] < 0)
				count++;
			else
				break;

		}

		if (count % 2 == 0)
			return new String(btf, 0, len, "gbk");
		else
			return new String(btf, 0, len - 1, "gbk");

	}

}

以上,謝謝觀看