在 Java 中,字符串 "abcd" 與字符串 "ab你好" 的長度一樣,是四個字符。 但對應的字節數不同,一個漢字占兩個字節。 定義一個方法,按照最大的字節數來取子串。 如: 對於 "ab你好",如果取三個字節,那麼子串就是 ab 與"你"字的半個, 那麼半個就要捨棄,如果與四個字節就是" ab 你",取五個字節還是" ab 你"。
import java.io.IOException;
public class EncodeTest {
public static void main(String[] args) throws IOException {
String str = "ab你好";
int len = str.getBytes("GBK").length;
for(int x = 0; x < len; x++) {
System.out.println((x + 1) + " Result: " + cutStringByByte(str, x + 1));
}
}
public static String cutStringByByte(String str, int len) throws IOException {
byte[] buf = str.getBytes("GBK");
int count = 0;
for(int x = len - 1; x >= 0; x--) {
if(buf[x] < 0)
count++;
else
break;
}
if(count % 2 == 0) {
return new String(buf, 0, len);
} else {
return new String(buf, 0, len - 1, "GBK");
}
}
}
打印結果
1 Result: a
2 Result: ab
3 Result: ab
4 Result: ab你
5 Result: ab你
6 Result: ab你好