简体   繁体   English

Java,将文本分类为行

[英]Java, sort text into lines

I'm writing a code that read a text from a file and then sort it into lines of max specific width. 我正在编写一个从文件中读取文本,然后将其排序为最大特定宽度的行的代码。

Example: a text that contains "aaaa bbbb cccc dddd" 示例:包含“ aaaa bbbb cccc dddd”的文本

specified width is 16 指定的宽度为16

so the output should be 所以输出应该是

aaaa bbbb cccc //width is only 14, if dddd is added, it would be longer than 16.

dddd

My approach: read the text and assign it to a string 我的方法:阅读文本并将其分配给字符串

Scanner input_OUT = new Scanner(new File("abc"));

PrintStream output = new PrintStream("abc");
.
.


 while (input_OUT.hasNextLine()) {
            str = input_OUT.nextLine();
        }

String s = "";

while(input_OUT.hasNext()) { // get words if it still have

            if (s.length() + input_OUT.next().length() > width) { 
                s = str.substring(0,s.length());
                output.println(s);
                str = str.substring(s.length()+1,str.length());
                s = "";
            }
            else {
                s += input_OUT.next();
            }

        }

Although it compiles. 虽然可以编译。 But the file doesn't show any output. 但是该文件未显示任何输出。 I think my code is not right. 我认为我的代码不正确。 I know there is options for stringbuild, string split, array. 我知道有用于stringbuild,字符串拆分,数组的选项。 But i'm now allowed to do that. 但是我现在被允许这样做。

The first issue is within this loop, assuming there is more than one thing being scanned from the file this approach won't work. 第一个问题是在此循环内,假设从文件中扫描了多个内容,则此方法将行不通。

String str;
while (input_OUT.hasNextLine()) {
   str = input_OUT.nextLine();
}

All you are doing is resetting str to the next element scanned. 您要做的就是将str重置为下一个扫描的元素。

A better approach would be to store file input into an array of Strings. 更好的方法是将文件输入存储到字符串数组中。

String str;   
String S[] = new String[#stringsInFile];
int i = 0;
while (input_OUT.hasNextLine()) {
   str = input_OUT.nextLine();
   S[i] = str;
   i++
}

Now all you have to do is manipulate the array S[] and then output to your output file. 现在,您要做的就是操作数组S [],然后将其输出到输出文件。

Noted in comments you said you can't an array. 在注释中指出您说您不能使用数组。 Lets just keep adding to S then and allow you to perform manipulations on S . 让我们继续添加到S然后允许您对S进行操作。 The approach: 该方法:

 String str;
 String S = "";    
 while (input_OUT.hasNextLine()) {
    str = input_OUT.nextLine();
    S = S +" "+ str; //This will keep adding onto S until hasNextLine is false
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM