java - 如何检查文本文件是否包含单个字符串或两个字符串?

标签 java string

假设我有一个文本文件,每行有两个字符串:

New York 52.523405 13.4114
San Antonio 41.387917 2.169919
Los Angeles 51.050991 13.733634

这是我将字符串从行中分离出来的代码:

for (int i = 0; i < noOfStores;i++){
    nextLine = console.readLine();
    nextLine = nextLine.trim();
    String temp[] = nextLine.split(" ");
    String Word = temp[0] + " " + temp[1];
    storeNames[i] = firstWord;
    latitudes[i] = Double.parseDouble(temp[2]);
    longitudes[i] = Double.parseDouble(temp[3]);
}

但是如果文本文件每一行只包含一个字符串,如下所示:

Berlin 52.523405 13.4114
Barcelona 41.387917 2.169919
Dresden 51.050991 13.733634

如何在读取文本文件时检查它是否包含一个或两个字符串?

最佳答案

使用split(""),获取返回的数组长度,然后解析数组中的最后两个String数组项,项length - 1length - 2,作为 double ,然后迭代最后两项之前的剩余字符串项,并将它们组合为城市字符串。比如,

for (int i = 0; i < noOfStores;i++){
    nextLine = console.readLine();
    nextLine = nextLine.trim();
    String temp[] = nextLine.split(" ");
    int length = temp.length;
    if (length < 3) {
        // output is not as expected; throw some type of exception here.
    }
    latitudes[i] = Double.parseDouble(temp[length - 2]);
    longitudes[i] = Double.parseDouble(temp[length - 1]);

    // this should handle city names with 1, 2 or any number of tokens
    StringBuilder wordSb = new StringBuilder();
    for (int j = 0; j < length - 2; j++) {
       wordSb.append(temp[j]);
       if (j != length - 3) {
          wordSb.append(" ");
       }
    }
    storeNames[i] = wordSb.toString();
}

关于java - 如何检查文本文件是否包含单个字符串或两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280242/

相关文章:

java - 如何在 Java 中读取/转换 InputStream 为字符串?

java - 在 GUI 中打开另一个 .java 文件

java - 如何使用java代码访问报表中的元素

java - JButton 仅在可见性设置为 True-Java 时才起作用

javascript - 在字符串变量中的字符之前插入几个字符(javascript)

c - 为什么 %[^\n]s 在循环中不起作用?

php - 在 PHP 中删除字符串开头的几个字符?

wpf - 从 GridViewColumn 访问 GridViewColumnHeader 对象

java - 在 Spring bean 中定义枚举映射

java - maven在eclipse jre中安装错误: