Java将空格添加到空白区域

时间:2017-11-24 00:44:38

标签: java

我有一个看起来无法解决的小问题:

GOAL:通过向单个空格字符添加空格来对ArrayList中的行(字符串)进行对齐,以使文本得到合理化所需的数量。

package com.mycompany.app;

import java.util.ArrayList; import java.util.List;

公共类MaxLengthLine {

String[] words;
int size;
int qtySpaces;
public MaxLengthLine (String text, int size){
    this.words = text.split(" ");
    this.size = size;
}
List<String> lines = new ArrayList<String>();
public void lineResize() {


    int index = 0;
    for (int i = 0; i < words.length - index; i++){
        String curLine = "";
    while((curLine + words[index]).length() <= size){
        curLine += words[index] + " ";
        index++;
    }

    curLine = curLine.substring(0, curLine.length()-1);
    lines.add(curLine);
    }

    String curLine = "";
    while(index < words.length){
        curLine += words[index] + " ";
        index++;
    }

    curLine = curLine.substring(0, curLine.length()-1);
    lines.add(curLine);

}

public void lineJustify() {
    for (int i = 0; i < lines.size(); i++){
        while (lines.get(i).length() < size){
            String test = lines.get(i).replaceFirst(" ", "  ");

            lines.set(i, test);
        }
    }
}

public String getTextFull (){
    String output = "";
    for(int i = 0; i < lines.size();i++){
        output += lines.get(i) + "\n";
    }
    while (output.contains("  ")){
        output = output.replace("  ", " ");
    }
    return output;
}

}

这段代码是我最初想到的最直接的解决方案(除了我已经尝试了很多其他的),但由于某种原因,结果会保持不变。

实际输出:

In the beginning God created the heavens
and the earth. Now the earth was
formless and empty, darkness was over
the surface of the deep, and the Spirit
of God was hovering over the waters.

And God said, "Let there be light," and
there was light. God saw that the light
was good, and he separated the light
from the darkness. God called the light
"day," and the darkness he called
"night." And there was evening, and
there was morning - the first day.

期望的输出:

In the beginning God created the heavens
and   the  earth.   Now  the  earth  was
formless  and empty,  darkness was  over
the  surface of the deep, and the Spirit
of  God was  hovering over  the  waters.

And  God said, "Let there be light," and
there  was light. God saw that the light
was  good, and  he separated  the  light
from  the darkness. God called the light
"day,"   and  the   darkness  he  called
"night."  And  there  was  evening,  and
there  was  morning  -  the  first  day.

编辑:输入:

起初,上帝创造了天地。现在地球是无形的,空虚的,黑暗笼罩在深处,上帝的灵正在水面上空盘旋。 上帝说:“有光明,”有光。上帝看到光是好的,他将光与黑暗分开。上帝称光为“白昼”,黑暗称之为“夜晚”。有傍晚,有早晨 - 第一天。

(我已经有代码在40个字符处正确地打破了行而不会破坏单词,所以最后一部分是用于将文本证明为40个字符的函数)

编辑2:我改变了整个班级的代码更清晰,我的teste上设置的大小是40。

2 个答案:

答案 0 :(得分:1)

public static List<String> justifyLines(String input, int lineLength) {
    String[] words = input.split(" ");
    List<String> result = new ArrayList<>();
    StringBuilder line = new StringBuilder();
    //here we store positions of all spaces in the current line to add more spaces there
    List<Integer> spacesPositions = new ArrayList<>();
    for (String word : words) {
        if (word.length() <= lineLength - line.length()) {
            line.append(word).append(" ");
            spacesPositions.add(line.length() - 1);
        } else {
            result.add(justifyLine(line, lineLength, spacesPositions));
            line.setLength(0);
            spacesPositions.clear();
            line.append(word).append(" ");
            spacesPositions.add(line.length() - 1);
        }
    }
    if (line.length() > 0) {
        result.add(justifyLine(line, lineLength, spacesPositions));
    }
    return result;
}

private static String justifyLine(StringBuilder line, int lineLength, List<Integer> spacesPositions) {
    //if line ends with space - remove it
    if (line.lastIndexOf(" ") == line.length() - 1) line.setLength(line.length() - 1);
    int spacesToAdd = lineLength - line.length();
    for (int j = 0; j < spacesToAdd; j++) {
        //It's the most complicated part, but I'll try to explain
        line.insert(
                // We're adding one space to each space in the line and then, if there are still spaces to insert,
                // repeating this process from the beginning - that's why we're using %
                spacesPositions.get(j % (spacesPositions.size() - 1))
                        // But each time we insert a new space, we need to take it into account for the following positions
                        // j % (spacesPositions.size() - 1) is the number of space in the line
                        // j / (spacesPositions.size() - 1) + 1 is the iteration number
                        + j % (spacesPositions.size() - 1) * (j / (spacesPositions.size() - 1) + 1), " ");
    }
    return line.toString();
}

所以for (String s : justifyLines("In the beginning...", 40)) System.out.println(s);打印:

In the beginning God created the heavens
and   the   earth.  Now  the  earth  was
formless  and  empty,  darkness was over
the  surface of the deep, and the Spirit
of God was hovering over the waters. And
God  said,  "Let  there  be  light," and
there  was light. God saw that the light
was  good,  and  he  separated the light
from  the darkness. God called the light
"day,"   and   the  darkness  he  called
"night."  And  there  was  evening,  and
there  was  morning  -  the  first  day.

答案 1 :(得分:0)

来自Java String class:

  

public String replaceFirst(String regex,                              字符串替换)

     

将与给定正则表达式匹配的此字符串的第一个子字符串替换为给定的替换。

所以你需要给它一个正则表达式,而不是空间本身。在java中,对于空格的正则表达式是&#34; \ s&#34;

String test = lines.get(i).replaceFirst("\\s", " ");

另外,作为一个需要考虑的事项,replaceFirst只替换匹配正则表达式的第一个子字符串,因此这段代码只会将空格添加到您找到的第一个空格中,而不是像您希望的那样均匀分布(因为第一个空格是双重空间&#34;&#34;仍将匹配正则表达式&#34; \ s&#34;。)

请检查一下。