- package com.itheima.test;
- import java.io.IOException;
- public class CutStringDemo {
- public static void main(String[] args) throws IOException {
- String string = "ab你cd好";
- int length1 = string.getBytes("UTF-8").length;
- for (int x = 0; x < length1; x++) {
- System.out.println("UTF-8截取到第" + (x + 1) + "个字节的内容是:" + CutStringByBytesUTF8(string, x + 1));
- }
-
- int length2 = string.getBytes("GBK").length;
- for (int x = 0; x < length2; x++) {
- System.out.println("GBK截取到第" + (x + 1) + "个字节的内容是:" + CutStringByBytes(string, x + 1));
- }
- }
-
- public static String CutStringByBytesUTF8(String string, int len) throws IOException {
- // 将字符串转换成字节数组
- byte[] buf = string.getBytes("UTF-8");
- int count = 0;
- for (int i = len - 1; i >= 0; i--) {//从最后的角标开始取值
- if (buf[i] < 0)
- count++;
- else // 判断,如果截取到的字节不小于零,就不用判断了。
- break;
- }
- if (count % 3 == 0) {
- return new String(buf, 0, len, "UTF-8");
- } else if(count % 3 == 1 ){
- return new String(buf, 0, len - 1, "UTF-8");
- }else {
- return new String(buf, 0, len - 2, "UTF-8");
- }
- }
-
-
-
-
- public static String CutStringByBytes(String string, int len) throws IOException {
- // 将字符串转换成字节数组
- byte[] buf = string.getBytes("GBK");
- int count = 0;
- for (int i = len - 1; i >= 0; i--) {//从最后的角标开始取值
- if (buf[i] < 0)
- count++;
- else // 判断,如果截取到的字节不小于零,就不用判断了。
- break;
- }
- if (count % 2 == 0) {
- return new String(buf, 0, len, "GBK");
- } else {
- return new String(buf, 0, len - 1, "GBK");
- }
- }
- }
复制代码
|