在网上有这样的一道面试题:就是输出一个字符串(含有中文)和一个整数 要求输出该指定整数长字节的字符串。
例如:
输入:he中国 2
输出:he
输入:he中国 3
输出:he
输入:he中国 4
输出:he中
这道题的主要难点就是对中文的处理中,一个中文是两个字节,对于中文的截取如果是1个字节就要舍弃掉,否则就保留。
代码:
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println("请输入一个字符串");
String s =new Scanner(System.in).nextLine();
System.out.println("请输入要截取的长度");
int n =new Scanner(System.in).nextInt();
pri(s,n);
}
private static void pri(String s, int n) throws UnsupportedEncodingException {
byte[] b = s.getBytes("gbk");
//定义count1接收数组正数出现的次数
//定义count2接受数组负数出现的次数
int count1 = 0;
int count2 =0;
for(int i = 0;i<=n-1;i++){
if(b[i]>0){
count1+=1;
}else{
count2+=1;
}
}
//正数出现说明是字符计入需截取长度中,负数出现一次则不计入,出现两次,说明是一个汉字,截取长度+1
int sum = count1+ (int)(count2/2);
String s3=s.substring(0, sum);
System.out.println(s3);
}
}