code小学生

导航

JAVA按照字节截取字符串子串

  今天做了一道按字节截取字符串的题目, 写个博客记录一下。

  

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) throws UnsupportedEncodingException {

        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        // 利用getBytes方法 将 getBytes 转换为 byte[]
        byte[] str2bytes = str.getBytes("gb2312");// gb2312 中文为2个字节 //UTF-8中文为3个字节

        int fromInd = sc.nextInt();
        int endInd = sc.nextInt();

        var newStr = new Solution();
        newStr.getStr(str2bytes, fromInd, endInd);
    }
    public void getStr(byte[] bytes, int fromInd, int endInd) throws UnsupportedEncodingException {
        // 问题: 如何得知 fromInd 是中文?(经过测试 可知 gb2312 编码中 中文字符小于0 )
        // 问题:如果是中文 如何得知 fromInd 是前一个字节还是后一个字节?
        // (可以利用 当前fromInd - 前面 单个字节 的数量 除2取余 若为 1 则 fromInd + 1)

        fromInd = (new Solution().indJudge(bytes, fromInd));
        endInd = (new Solution().indJudge(bytes, endInd));
        System.out.println(new String(bytes, fromInd, endInd - fromInd, "gb2312"));
    }
    public int indJudge(byte[] bytes, int index){
        int singleCount = 0;
        for(int i = 0; i < index; i++){
            if(bytes[i] > 0 )
                singleCount++;
        }
        index = (index - singleCount) % 2 == 0? index: index+1;
        return index;
    }

}

 

posted on 2020-04-29 14:45  code小学生  阅读(534)  评论(0)    收藏  举报