题目描述:
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF"6,应该输出为"我ABC"而不是"我ABC+汉的半个"。
输入描述:
输入待截取的字符串及长度
输出描述:
截取后的字符串
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.next();
int num = scanner.nextInt();
int count = 0;
String[] strs = str.split("");
String res = "";
for (String s : strs)
{
if (!isChinese(s))
count++;
else
count += 2;
if (count <= num)
res += s;
else
break;
}
System.out.println(res);
}
}
public static boolean isChinese(String s)
{
return s.length() == s.getBytes().length ? false : true;
}
}