gpt4 book ai didi

java - 如何检查不同类型的扫描仪字符串拆分

转载 作者:行者123 更新时间:2023-12-02 09:54:32 26 4
gpt4 key购买 nike

假设您有一个包含三列的文本文件,每列都有数据。有时列用空格分隔,有时用制表符分隔,如下所示:

带空格:

1 250 643
2 446 116
3 199 292
4 801 171

带标签:

1   352500  371500
2 381500 374500
3 304000 384500
4 431000 394000
5 355000 404000

假设后两列包含 x 和 y 坐标,它们存储在位置对象 Locationlocations[] 的某个数组中,其中 Location 有一些构造函数,例如 公共(public)位置(双x,双y)。因此,我们解析这些坐标并将它们存储在 Location 数组中,如下所示:

Scanner s = new Scanner("someFile.txt");
Location locations = new Location[numberOfRowsInFile];
int i = 0;
while(i < numerOfRowsInFile) {
String line = s.nextLine();
String[] coordinate = line.split("\t");
locations[i++] = new Location(Double.parseDouble(coordinate[1]),Double.parseDouble(coordinate[2])); //Parse coordinates
}

现在这是我的问题。在 String[] axis = line.split("\t"); 行上,当列由制表符分隔时,这适用于文本文件,但不适用于列由空格分隔时。在这种情况下,我需要 String[] axis = line.split("");

如何检查哪个分隔符有效?像这样的事情:

if (line.validSplit() == "\t")
String[] coordinate = line.split("\t");
else if (line.validSplit() == " ")
String[] coordinate = line.split(" ");

最佳答案

由于 split() 使用正则表达式,

Scanner s = new Scanner("someFile.txt");
Location locations = new Location[numberOfRowsInFile];
int i = 0;
while(i < numerOfRowsInFile) {
String line = s.nextLine();
String[] coordinate = line.split("\\s+");
locations[i++] = new Location(Double.parseDouble(coordinate[1]),Double.parseDouble(coordinate[2])); //Parse coordinates
}

\\s+ => 用 1 个或多个空格分割字符串。

关于java - 如何检查不同类型的扫描仪字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099799/

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