gpt4 book ai didi

java - 如果检测到分隔符,则在行尾添加空格?

转载 作者:行者123 更新时间:2023-11-30 02:43:10 26 4
gpt4 key购买 nike

我创建了一个方法,允许我读取文本文件并将各个单词放入其自己的元素中,并用 | 分隔。

示例:

0 | john | smith | potato |

上面的内容会变成:

0
john
smith
potato

如果检测到 |,有没有办法在行尾添加空格 ()?我希望以这种方式完成,这样我就可以实现这一目标:

0
john
smith
potato
<-- empty spot goes here -->

这是我到目前为止所拥有的:

public static String[] read() throws IOException {
String str = null;
List<String> list = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader("test.txt"));
while ((str = in.readLine()) != null) {
for (String token : str.split("\\|")) {
list.add(token);
}
}
}

最佳答案

String.split 作为修剪前导空单元格的奇怪习惯,所以如果您有

potato||

结果将是

[potato]

但是您可以告诉不要使用 split("\\|", -1) 来修剪它。这将导致

[potato,,] //3 cells

阅读doc of Split了解更多。这是限制解释:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

关于java - 如果检测到分隔符,则在行尾添加空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41038317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com