截取字符串以多行的形式输出

来源:互联网 发布:猪八戒考试软件下载 编辑:程序博客网 时间:2024/06/15 02:22

问题描述:输入一个字符串(包括汉字和英文字母以及其他符号)以及每行的字节数。输出为一个字符串被分割为多行输出。

举例:

Please input string:
dasa大大dad
Please input string number per line:
4
Print the string as 4 byte per line:
dasa
大大
dad

这里需要注意的是:中文字符占两个字节,英文字符占一个字节。汉字不能输出半个(也就是说实际一行输出的字节等于或比要求少一个)。

java代码实现如下:

package test1;import java.util.Scanner;public class InterceptionStr {static String ss;//用于记录输入的字符串static int n; //用于记录每行输出的字节数public static void main(String[] args) {System.out.println("Please input string:");//提示用户输入要截取的字符串Scanner inStr = new Scanner(System.in);ss = inStr.next();//将用户输入以字符串的形式取出System.out.println("Please input string number per line:");//提示用户输入每行的字节数Scanner inByte = new Scanner(System.in);n = inByte.nextInt();//以整数的形式取出用户输入interception(setValue());//调用函数完成格式化输出}//将用户的输入转换成字符串数组便于处理public static String[] setValue(){String[] string = new String[ss.length()];for (int i = 0; i < string.length; i++){string[i] = ss.substring(i, i + 1);// 左闭右开}return string;}public static void interception(String[] string){int count = 0;String m = "[\u4e00-\u9fa5]";//汉字的正则表达式System.out.println("Print the string as " + n +" byte per line:");for (int i = 0; i < string.length; i++){if (string[i].matches(m))count += 2;//汉字占两个字节elsecount += 1;//其他字符占一个字节if (count < n)System.out.print(string[i]);else if (count == n){System.out.print(string[i]);count = 0;System.out.println();}else{count = 0;System.out.println();}}}}