需求:按给定字节数截取含有中英文的字符串,最后一个字节如果截取的是中文则不截取,是英文则截取实现代码如下(未进行空字符串或非法字节数等异常判断)
1 import java.util.ArrayList;
2 import java.util.List;
3 import java.util.Scanner;
4
5 /**
6 * Created by ycl on 2017-8-18 21:01:16.
7 */
8 public class TestA {
9 public static void main(String[] args) {
10 Scanner sc =
new Scanner(System.in);
11 System.out.println("字符串:"
);
12 String str =
sc.nextLine();
13 System.out.println("输入截取字节数:"
);
14 int count =
sc.nextInt();
15 getSubStrByByte(str, count);
16
17 }
18
19 /**
20 * @param str 接收输入的中英文字符串
21 * @param byteLen 接收要截取的字节数
22 */
23 public static void getSubStrByByte(String str,
int byteLen) {
24 byte[] bytes =
str.getBytes();
25 int count = 0;
//已经遍历出的字节数
26 String tempStr = "";
//最终输出字符串
27 List<Byte> list =
new ArrayList<Byte>();
//临时存放一个中文每一个字节的列表
28 for (
byte b : bytes) {
29 if (b >= 0) {
//大于等于0表示英文
30 tempStr +=
new String(
new byte[]{b});
//直接追加到输出字符串
31 count++
;
32 }
else {
33 list.add(b);
//小于0表示中文,并将字节添加到临时列表中
34 if (list.size() == 3) {
//当列表长度为3时,先转换为字符数组,再转为字符并追加到输出字符串
35 byte[] temp =
new byte[3
];
36 int i = 0
;
37 for (Byte l : list) {
38 temp[i] = (
byte) l;
39 i++
;
40 }
41 tempStr +=
new String(temp);
42 count += 2;
//一个中文字节数加2
43 list.clear();
//清空临时列表
44 }
45 }
46 if (count == byteLen) {
//当遍历的字节数等于需要截取的字节数时则输出,并跳出循环
47 System.out.println(tempStr);
48 break;
49 }
50 //当遍历的字节数减需要截取的字节数=1时则说明最后一个字符为中文,输出并跳出循环
51 else if ((count - byteLen == 1
)) {
52 System.out.println(tempStr.substring(0, tempStr.length() - 1
));
53 break;
54 }
55 }
56 }
57 }
转载于:https://www.cnblogs.com/BeautyInWholeLife/p/7392316.html