【问题标题】:Java adding whitespace to whitespaceJava将空格添加到空格
【发布时间】:2017-11-24 00:44:38
【问题描述】:

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

目标:通过向单个空白字符添加空格来对齐 ArrayList 中的行(字符串),以使文本对齐。

package com.mycompany.app;

导入 java.util.ArrayList; 导入 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。

【问题讨论】:

  • 还有...示例输入?
  • 没有什么可以证明的——首先你想要达到的宽度在哪里?
  • 你在哪里计算变量size
  • 对不起,编辑了更多信息,如果需要我可以粘贴整个课程,我只是认为没有必要
  • 为什么这看起来“无法解决”?如果你能用手做,你可以用代码来做。

标签: java


【解决方案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.

【讨论】:

  • 非常感谢,您已经非常接近了,但是这段代码仍然存在 2 个问题,问题 1 示例: 第 1 行:起初上帝创造了它应该适合“天堂”这个词行,但是代码在右边加了一个空格,看看它应该是怎样的: 起初上帝创造了诸天 问题 2 例子: 最后一行:第一天。它应该对最后一行做同样的事情,所以应该看起来像这样something:第一天。也许这个问题,我可以再做一次插入的事情,但是我真的找不到第一个
  • 您对额外空间的看法是正确的。我已经修好了。并且还为最后一行添加了对齐。检查编辑的答案!
【解决方案2】:

来自 Java String 类:

公共字符串替换第一(字符串正则表达式, 字符串替换)

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

所以你需要给它一个正则表达式,而不是空间本身。在 java 正则表达式中,空格是 "\s"

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

另外,作为要考虑的事情,replaceFirst 仅替换与正则表达式匹配的第一个子字符串,因此此代码只会将空格添加到您找到的第一个空格,而不是像您希望的那样均匀分布(因为双空格“”仍将匹配正则表达式“\s”。)

检查一下。

【讨论】:

  • 感谢您的回答,但是空格的标识不是问题,问题是替换,例如,如果我将替换替换为“aa”之类的字母,它会正确替换,但是由于某种原因,空格没有加起来。如果我放置 1 或 10 个空格,则输出中仅保留 1 个。知道为什么吗?
猜你喜欢
  • 2018-06-13
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多