0

这是整个程序的一部分。我遇到的问题是当给定n时,程序应该在当前或最后一个空格处插入一个换行符,以确保字符数(空格不包括在计数中)在a之前永远不会超过n插入换行符。它当前的行为是它将用换行符分割单词。保证:n 永远不会超过最大单词的字符数。示例:n = 9,成为或不成为这是个问题。想要的行为:

To be or not
to be that
is the
question

当前行为:

To be or not
 to be th
at is
 the question

如您所见,空格并没有像预期的那样被替换,并且单词被换行符打破。我在办公桌上检查了很多次,但我似乎找不到问题所在。请帮忙!

public class Separator {

    int n; //the int in front of read line
    int cCount = 0;  //character counter
    int i;
    int lastSpc;
    char c;  //for character iterator
    String linePart;

    public String separate(int n, String linePart) {
        StringBuilder finLine = new StringBuilder(linePart);

        for (i = 0; i < linePart.length(); i++) {  //inspects each character in string.
            c = linePart.charAt(i);

            if (c == ' ') {                          //determines whether or not char is a space
                if (cCount == n ) {                  //checks char count
                    finLine.replace(i, i, System.lineSeparator());   //adds new line if char count is reached right before space.
                    cCount = 0;
                    lastSpc = i;
                }
                else {
                    lastSpc = i;                     //assigns index to variable so no need to reverse through string.
                }
            }
            else {
                cCount++;
                if (cCount == n) {                      //if char count is reached while inspecting letter, 
                    finLine.replace(lastSpc, lastSpc, System.lineSeparator());      //replaces last space with new line char
                    cCount = i - lastSpc;
                }
            }
        }
        return finLine.toString();
    }
}
4

1 回答 1

0

添加第一个换行符后,finLine 的索引不再匹配 linePart 的索引。使用 finLine 而不是 linePart 以保持索引一致。

public String separate(int n, String linePart) {
    StringBuilder finLine = new StringBuilder(linePart);
    int lines_added = 0;
    for (i = 0; i < finLine.length(); i++) {  //inspects each character in string.
        c = finLine.charAt(i);

        if (c == ' ') {                          //determines whether or not char is a space
            if (cCount == n ) {                  //checks char count
                finLine.replace(i, i+1, System.lineSeparator());   //adds new line if char count is reached right before space.
                cCount = 0;
                lastSpc = i ;
            }
            else {
                lastSpc = i;                     //assigns index to variable so no need to reverse through string.
            }
        }
        else {
            cCount++;
            if (cCount == n) {                      //if char count is reached while inspecting letter, 
                finLine.replace(lastSpc, lastSpc+1, System.lineSeparator());      //replaces last space with new line char
                cCount = i - lastSpc;
            }
        }
    }
    return finLine.toString();
}
于 2015-09-21T22:01:34.877 回答