【问题标题】:How to check for different kinds of scanner string splits如何检查不同类型的扫描仪字符串拆分
【发布时间】:2019-05-12 13:38:31
【问题描述】:

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

带空格:

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 坐标,它们存储在某个位置对象数组Location locations[] 中,其中Location 有一些构造函数,例如public Location(double x, double 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[] coordinate = line.split("\t"); 行上,当列由制表符分隔时,这适用于文本文件,但在列由空格分隔时无效。在这种情况下,我需要String[] coordinate = line.split(" ");

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

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

【问题讨论】:

  • 来吧,只需将两者结合到[ \t] 就可以了。没有必要让它比需要的更复杂。
  • 您也可以使用扫描仪直接读取整数。这样你就不需要解析行了。
  • line.split("\\s+") 不工作吗?
  • @BlackPearl 是的,谢谢。我不知道"\\s+" 是什么?
  • \\s 表示空格。 \\s+ 表示 1 个或多个空格。我已将其添加为答案。

标签: java string file java.util.scanner


【解决方案1】:

由于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 个或多个空格分割字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多