0

我正在从一个包含整个段落的单独文件中读取输入。我将段落中的单词存储在列表中。我的目标是从单独的文件中打印出整个段落,每行不超过字符的字符限制。我正在使用以下方法遍历列表:

for (String word: words)

我不确定如何编写字符限制的代码。我正在考虑使用StringBuffer方法,但我不确定。有任何想法吗?

4

4 回答 4

2

这似乎是你想要的:Java's BreakIterator

于 2013-10-07T21:05:54.480 回答
0

您确实可以使用 StringBuffer (或StringBuilder如果您不关心线程安全)在遇到单词时临时保存它们。要强制执行字符限制,您可以在将单词添加到缓冲区之前计算添加单词的字符数。达到限制后,刷新缓冲区(进入输出缓冲区/文件)并重新开始。

这是我刚做的又快又脏的东西:

import java.util.Scanner;

public class CharLimit {

    static int LIMIT = 79;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder buffer = new StringBuilder(LIMIT);

        while (sc.hasNextLine()) {
            Scanner sc2 = new Scanner(sc.nextLine());
            while (sc2.hasNext()) {
                String nextWord = sc2.next();
                if ((buffer.length() + nextWord.length() + 1) > LIMIT) {
                    // we would have exceeded the line limit; flush
                    buffer.append('\n');
                    System.out.print(buffer.toString());

                    buffer = new StringBuilder(nextWord);
                }
                else {
                    buffer.append((buffer.length() == 0 ? "" : " ") + nextWord);
                }
            }
        }

        if (buffer.length() > 0) {
            System.out.print(buffer.toString() + "\n");
        }

        System.exit(0);
    }

}

例子:

???:/tmp$ cat input

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit anim id est laborum.

???:/tmp$ java CharLimit < input 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.

请注意,这不考虑长于预配置限制的“单词”令牌。

于 2013-10-07T21:03:06.410 回答
0

我个人的实现。从我的牛仔时代开始,代码就很旧了,但它可以工作。随心所欲地调整它。

private static final int LINE_LENGTH = 30;
private static final String SPACE = " ";
private static final String EMPTY_STRING = "";

/**
 * Formats the given input text: <br />
 * - Wraps text to lines of maximum <code>LINE_LENGTH</code> <br />
 * - Adds newline characters at each line ending <br />
 * - Returns as a string
 */
public static String getPreviewLines(final String input) 
{
    final StringTokenizer token = new StringTokenizer(input, SPACE);
    final StringBuilder output = new StringBuilder(input.length());

    int lineLen = 0;

    while (token.hasMoreTokens()) 
    {
        final String word = token.nextToken() + SPACE;

        if (lineLen + word.length() - 1 > LINE_LENGTH) 
        {
            output.append(System.lineSeparator());
            lineLen = 0;
        }

        output.append(word);

        if (word.contains(System.lineSeparator())) 
            lineLen = word.replaceAll("\\s+", EMPTY_STRING).length(); //$NON-NLS-1$
        else
            lineLen += word.length();
    }

    return output.toString();
}
于 2013-10-07T21:15:47.540 回答
0
    public static String lineSeparator = System.getProperty("line.separator");
    public static int size = 10;
    /**
     * Main Method
     * @param args
     */
    public static void main(String[] args) {
    String read = "enter any text here or read it from somewhere else the idea here is to split as many words you want and print it in the format you want";        
    String[] wordArray = read.trim().split(" ");        
    printBySize(size,wordArray);

    }

    private static void printBySize(int size, String[] wordArray) {
        StringBuilder bld = new StringBuilder(size);
        for(int i=0; i<wordArray.length;i++) {

            String word = wordArray[i];

            if ((bld.length() + word.length()) >= size) {
                //if yes add a new line and create a new builder for the new line
                bld.append(lineSeparator);
                System.out.print(bld.toString());
                bld = new StringBuilder(word);
            }
            else {

                bld.append((bld.length() == 0 ? "" : " ") + word);
            }

        }
        System.out.println(bld.toString());
    }
于 2014-03-12T21:23:37.620 回答