你如何限制java中每一行的字符?

时间:2018-05-18 23:07:49

标签: java

我想知道如何限制每行中的字符。如果下一个单词太长而不适合 - 例如12个字符行,那么它将进入下一行。

import java.io.File;
import java.util.Scanner;

public class Programme {
    public static void main(String[] args)throws Exception {
        method1(args[0],args[1]);

    }
    public static void method1(String file, String n)throws 
Exception{
        Scanner sc = new Scanner(new File(file));
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String [] splitv = line.split(" ");
            char[] splitv2 = line.toCharArray();
            for (int i=0;i<Integer.parseInt(n);i++){
                System.out.print(splitv2[i]);
            }
            System.out.println("");
        }
    }    
}

这是一个未完成的程序,我希望它可以工作,例如,如果它获得一个文本文件,下面有文本和第二个参数&#34; n&#34;如12:

01 23 456 789 012 3 4 
56 78 9 0 12 34 56 789

程序输出为:

01 23 456
789 012 3 4
56 78 9 0 12
34 56 789

空格也是一个重要的字符,在这种情况下789不适合作为12个字符的行,因此它将在下一行打印。

1 个答案:

答案 0 :(得分:3)

将您的输入连接成一个字符串,然后使用lastIndexOf(' ', 12)找到要打破的空间。

String input = "01 23 456 789 012 3 4 56 78 9 0 12 34 56 789";
while (input.length() > 12) {
    int idx = input.lastIndexOf(' ', 12);
    System.out.println(input.substring(0, idx));
    input = input.substring(idx + 1);
}
System.out.println(input);

输出

01 23 456
789 012 3 4
56 78 9 0 12
34 56 789

如果文本可以包含长词,则需要额外的逻辑来防范它们。

String input = "123456789012345 6 789012345678901 234 567 8 9 01 23 4 5 67 89 01 234567890123456";
while (input.length() > 12) {
    int idx = input.lastIndexOf(' ', 12);
    if (idx == -1) { // too long word
        idx = input.indexOf(' ', 12);
        if (idx == -1) // last word
            break;
    }
    System.out.println(input.substring(0, idx));
    input = input.substring(idx + 1);
}
System.out.println(input);

输出

123456789012345
6
789012345678901
234 567 8 9
01 23 4 5 67
89 01
234567890123456

如果文本可以包含连续的空格,则应首先删除它们。

input = input.replaceAll("\\s+", " ").trim();