输入字节数,以字节方式截取字符串,避免半个汉字

思路分析:

1.开启扫描器对象,以扫描键盘输入的string字符串和输入的截取字节数

2.分解string字符串为byte字节存入字节数组里,以GBK形式获取字节

3.判断汉字个数,算法

4.输出截取的字节(本代码此处拼接为string字符串形式)


package dj练习;



import java.util.Scanner;


/**
 * 
 * @author LD
 *
 */


public class INTERCEPTBYTE {
static String d;
static String s;
static String e;
public static void main(String[] args) throws Exception {
INTERCEPTBYTE interceptbyte = new INTERCEPTBYTE();
interceptbyte.t();
}
public void t() throws Exception {
while (true) {
//开始键盘扫描
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符:");
//获取键盘输入
String line = scanner.nextLine();
//将键盘输入以GBK形式转换为字节
byte[] bytes = line.getBytes("GBK");
System.out.println("请输入截取长度:");
//获取键盘输入
int leight=scanner.nextInt();
//定义一个变量
int count=0;
//如果所要截取字符长度的值大于字符的长度或者小于零,打印错误
if (leight>bytes.length||leight<0) {
System.out.println("输入长度不正确:");
}
//for循环遍历截取个数,如果字节数组里面的值的艾斯码值大于零,创建新字符串对象,将值存入
for (int i = 0; i <leight; i++) {
if (bytes[i]>0) {
d = new String(bytes,0,leight,"GBK");
}
//同上,并记录次数
if (bytes[i]<0) {
count++;
s = new String(bytes,0,leight,"GBK");
}
}
//因为是GBK,所以以2为除数判断,
if (count%2==0) {
if (d!=null&&s!=null) {
System.out.println(d+s);
}
if (s==null) {
System.out.println(d);
}
if (d==null) {
System.out.println(s);
}
}else {
String t = new String(bytes,0,leight+1,"GBK");
if (d!=null&&t!=null) {
System.out.println(d+t);
}
if (d==null) {
System.out.println(t);
}
if (t==null) {
System.out.println(d);
}
}
}
}
}

猜你喜欢

转载自blog.csdn.net/liudasnb/article/details/80942674
今日推荐