- package com.str;
- class CopyStrByByte{
- private String str = ""; //字符串
- private int copyNum = 0; //要复制的字节数
- private String arrStr[]; //存放字符串拆分成的数组
- private int cutNum = 0; //已截取的字节数
- private int cc = 0; //str中中文字符数
- public CopyStrByByte(String str, int copyNum){
- this.str = str;
- this.copyNum = copyNum;
- }
- public String copyStr(){
- arrStr = str.split("");
- str = "";
- for (int i = 0; i <= arrStr.length; i++) {
- if (arrStr[i].getBytes().length == 1) {
- cutNum = cutNum + 1; //统计个数
- str = str + arrStr[i]; //获得非汉字子串
- } else if (arrStr[i].getBytes().length == 2) {
- cc = cc + 1; //统计汉字个数
- cutNum = cutNum + 2; //汉字字节数为2进行统计
- str = str + arrStr[i];
- }
- if (cutNum > copyNum) break; //已截取的字符数大于要截取的字符数
- }
- if(cutNum > copyNum)
- return str.substring(0, copyNum - cc);
- else
- return str;
- }
- }
- public class Truncate {
- public static void main(String[] args) {
- CopyStrByByte byByte = new CopyStrByByte("我ABC汉DEF", 6);
- System.out.println(byByte.copyStr());
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1808201614947.html
来源: http://www.codesnippet.cn/detail/1808201614947.html