package com.itheima;
/**
* 10、 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
* 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*
* @author 281167413@qq.com
*/
public class Test10 {
public static void main(String[] args) {
String srcStr1 = "我ABC";
String srcStr2 = "我ABC汉DEF";
splitString(srcStr1, 4);
splitString(srcStr2, 6);
}
public static void splitString(String src, int len) {
int byteNum = 0;
if (null == src) {
System.out.println("The source String is null!");
return;
}
byteNum = src.length();
byte bt[] = src.getBytes(); // 将String转换成byte字节数组
if (len > byteNum) {
len = byteNum;
}
// 判断是否出现了截半,截半的话字节对于的ASC码是小于0的值
if (bt[len] < 0) {
String subStrx = new String(bt, 0, --len);
System.out.println("subStrx==" + subStrx);
} else {
String subStrx = new String(bt, 0, len);
System.out.println("subStrx==" + subStrx);
}
}
}
ps:看比人博客上面的,具体的没操作过,
package com.demo.test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
//输入字符串
String str = sc.next();
//输入要截取的字节长度
int byteLength = sc.nextInt();
splitString(str,byteLength);
sc.close();
}
public static void splitString(String str, int byteLength) throws Exception{
//判断待截取的字符串的字节长度是否大于等于输入的字节长度
if (str.getBytes().length >= byteLength) {
//将字符串转为字符数组
char[] charArray = str.toCharArray();
String s = "";
for (int i = 0; i < byteLength; i++) {
//判断当前字符串s的字节长度是否与要截取的字节长度相等,若相等跳出循环
if (s.getBytes().length == byteLength) {
break;
//判断当前字符串s的字节长度是否小于要截取的字节长度,若小于继续拼接字符串
}else if (s.getBytes().length < byteLength) {
s += charArray[i];
}else {
//当前字符串字节长度大于要截取的字节长度,舍弃最后一个字符
s = s.substring(0, i-1);
break;
}
}
System.out.println(s);
}else {
System.out.println("输入的字节长度不能大于字符串的字节长度");
}
}
}
这个方法有个前提 必须是GBK编码 因为只有GBK 汉子才是2个字节 UTF-8就是3个字节
public static String buStr(String str,int l) {
byte b[] = str.getBytes();
byte[] a = new byte[l+1];
for(int i=0;i
if((b[i] < 0 || b[i] >127)&&i==l){//截取末位的汉子
System.out.println(b[i]+":我是非字符");
a[l]=b[i];
}
if(i==l) break;
}
return new String(a);
}