java面试: 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。

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

思路:

  1. 判断是否为空
  2. 不为空的话判断截取的字节数,如果字节数大于字符串长度,就设置为截取所有字节数的长度
  3. 截半的话对应字节的ASC码为小于0的数值
import java.util.Scanner;

public class TestAgricuter {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while(true){
		String str1 = scan.next();
		int n = scan.nextInt();
		str_split(str1, n);
		}
	}

	public static void str_split(String str1, int n) {
		if (str1 == null) {
			System.out.println("please input valid!");
			return;
		}
		int byte_all = 0;
		byte_all = str1.length();
		byte byte_[] = str1.getBytes();
		if (n > byte_all)
			n = byte_all;
		if (byte_[n - 1] < 0) {

		System.out.println("subStrx==" + new String(byte_,0, n-1));
		} else {
			System.out.println("subStrx==" + new String(byte_,0, n));
		}
	}
}

  

发布了233 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42565135/article/details/102819388
今日推荐