import java.util.Arrays;
import java.util.Scanner;
public class 截取字符串 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int a = scan.nextInt();
splitString(s,a);//分割字符串
}
private static void splitString(String s,int n) {
byte[] bt = s.getBytes();//先把字符串转换成byte数组,可以打印出来看[-50, -46, -54, -57, -42, -48, -71, -6, -56, -53, 105, 32, 108, 111, 118, 101, 32, 121, 111, 117],
//其实汉字在内存中占用2个字节,并且都为负数,两个负数组合成一个汉字,例如把byte数组byte[]{-50, -46}就可以转换成“我”这个汉字。
System.out.println(Arrays.toString(bt));
byte[] newStr = new byte[n];//声明数组
int i = 0;
int count = 0;
while( i < n ){
if(bt[i] > 0){
newStr[i] = bt[i];
i=i+1;
count++;
}else if( bt[i] < 0 && bt[i+1] < 0 ){
newStr[i] = bt[i];
count++;
if(i+1 < n){
newStr[i+1] = bt[i+1];
count++;
}else{
count--;
}
i = i+2;
}
}
byte[] result = new byte[count];
System.arraycopy(newStr, 0, result, 0, count);//数组copy真正的长度为count
String ss = new String(result);
System.out.println(ss);//打印数组
}
}
运行结果:
我是中国人i love you
16
[-50, -46, -54, -57, -42, -48, -71, -6, -56, -53, 105, 32, 108, 111, 118, 101, 32, 121, 111, 117]
我是中国人i love
运行结果:
我是中国人i love you
9
[-50, -46, -54, -57, -42, -48, -71, -6, -56, -53, 105, 32, 108, 111, 118, 101, 32, 121, 111, 117]
我是中国
截取字符串(编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输...)
最新推荐文章于 2021-08-10 21:04:13 发布