如何让一条线在某一点被切断,但在最近的空间分裂

问题描述 投票:0回答:2

我希望每行在 20 个字符过去后分开,但我希望它在最近的空间分开,所以句子只有完整的单词。

这是我的代码:

System.out.println("Please input a word: ");
            Scanner stringScanner = new Scanner(System.in);
            String input = stringScanner.nextLine();
            
            
            int numberOfCharacters = 20;
    
            for(int pos = numberOfCharacters; pos >= 0; pos --)
            {
                if(input.charAt(pos) == ' ')
                {
                    System.out.println(input.substring(0, pos)); 
                    System.out.println(input.substring(pos+1,21)); 
                }
            }
        }
    }

这是我得到的输出,不知道为什么:

请输入字词:

Hello there, I am doing some coding, I need some help
Hello there, I am
doi
Hello there, I
am doi
Hello there,
I am doi
Hello
there, I am doi
The output I want is:
Hello there, I am
doing some coding, 
I need some help

谢谢你的帮助。

java for-loop substring java.util.scanner
2个回答
1
投票

您可以采取的一种方法是:

str="some long string"
while (str can be safely split) {
   split off and print the left portion
   assign the right portion to str
}
print the remainder of str

如果你不想改变输入和管理位置,使用两个变量会更简单,一个 startPos 和一个 endPos。

str="some long string"
startPos=0, endPos=0
while (startPos < str.length) {
    determine endPos
    print substring from startPos to endPos
    move startPos to endPos+1
}

1
投票

这是一种方法。

String str = "What's in a name? That which we call a rose "
         + "By any other name would smell as sweet;";

List<String> list = splitLine(str, 20);
list.forEach(System.out::println);

版画

What's in a name?
That which we call
a rose By any other
name would smell as
sweet;
  • 分配一个
    List
    来保存子字符串
  • 循环直到线是
    blank
    或者如果剩余的段小于
    size
  • 现在检查从大小小于 1 开始的空格字符。
  • 将该子字符串添加到列表中并将该行更新到下一个起始位置。
public static List<String> splitLine(String line, int size) {
    List<String> list = new ArrayList<>();
    while (!line.isBlank()) {
        int len = Math.min(line.length(), size);
        if (len < size) {
            list.add(line);
            break;
        }
        while (line.charAt(--len) != ' ') {
           if (len == 0) {
             throw new 
                 IllegalArgumentException("\nWord length exceeds size specification");
           }
        }
        list.add(line.substring(0, len));
        line = line.substring(len+1);
    }
    return list;
}
© www.soinside.com 2019 - 2024. All rights reserved.