【Java】charset="utf-8"时,一个汉字占三个byte

实验程序:

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringSize {
    public static String cutShort(String str,int fixedBytes) throws UnsupportedEncodingException {
        final String charset="utf-8";
        
        byte[] arr=str.getBytes(charset);
        if(arr.length>fixedBytes) {
            byte[] newArr=Arrays.copyOfRange(arr, 0, fixedBytes);
            return new String(newArr,charset);
        }
        
        return str;
    }
    
    public static void main(String[] args) throws Exception{
        String str="饕餮貔貅虎兕耄耋前军夜渡姚河北已报生擒吐谷浑";
        System.out.println(cutShort(str,24));
    }
}

输出:

饕餮貔貅虎兕耄耋

8个汉字正好24个byte。

-END-

原文地址:https://www.cnblogs.com/heyang78/p/15354238.html