截取字符串(编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输...)

来源:互联网 发布:国信期货软件 编辑:程序博客网 时间:2024/05/17 21:46
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真正的长度为countString ss = new String(result);System.out.println(ss);//打印数组}}运行结果:我是中国人i love you16[-50, -46, -54, -57, -42, -48, -71, -6, -56, -53, 105, 32, 108, 111, 118, 101, 32, 121, 111, 117]我是中国人i love运行结果:我是中国人i love you9[-50, -46, -54, -57, -42, -48, -71, -6, -56, -53, 105, 32, 108, 111, 118, 101, 32, 121, 111, 117]我是中国

原创粉丝点击