【问题标题】:Using a character as a starting and ending point for a scanner使用字符作为扫描仪的起点和终点
【发布时间】:2014-09-13 18:21:58
【问题描述】:

所以我有一个像这样的文本文件

1 5 8 3 5 7 8 4 6 7 8 9 2 D 2 4 7 9 8 5

我一直在尝试做的是让扫描仪读取,直到它看到第一个“D”,然后处理后面的所有数字,直到它遇到第二个“D”。下次扫描仪查找时会出现这个问题起点是第三个“D”

非常感谢任何帮助。

【问题讨论】:

  • 请发布您的代码的当前状态。

标签: java java.util.scanner text-parsing


【解决方案1】:

你可以让the Scanner use "D" as the delimiter:

public static void main(String[] args) {
    String input = "1 5 8 D 3 5 7 8 D 4 6 7 8 9 D 2 D 2 4 7 9 8 5";
    Scanner sc = new Scanner(input).useDelimiter("D");
    while(sc.hasNext()) {
        sc.next(); // "1 5 8", "3 5 7 8", ...
    }
}

不清楚是否要跳过前导数字,但如果要这样做,只需在循环前调用一次 next() 即可。

【讨论】:

    【解决方案2】:

    你甚至可以这样做

    BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        new FileInputStream("something.txt") ));
    while(true){
        String line = reader.readLine();
        if(line==null)
            break;
        else{
            String arr[] = line.split("d");
            // arr contains 1 5 8 at 0 index 3 5 7  at index 1 and so on
        }
    }
    

    【讨论】:

      【解决方案3】:

      你有几个选择,这里有 3 个:

      1) 使用阅读器并检查每个字符:

      Reader in = ...; // Obtain an instance, likely getting an InputStream and a CharSet.
      CharArrayWriter buffer = new CharArrayWriter();
      while (in.ready) { // Safe because you said you're reading from a File
          char c = in.read();
          if (Character.isLetter(c)) {
              char[] lastRead = buffer.toCharArray();
              buffer.reset();
          } else {
              buffer.append(c);
          }
      }
      

      2) 使用String.split 函数。此方法要求您将文件完全读入String

      String[] parts = myFileContent.split("[a-zA-Z]");
      

      3) 使用StringTokenizer,然后提供找到的字符串的Enumeration。这也要求您首先阅读整个File 的内容。

      StringTokenizer str = new StringTokenizer(myFileContent, "abc....Z"); // The construction of the set of delimiters can be automatized with a loop over a char for example.
      while (str.hasMoreTokens()) {
          String somePart = str.nextToken();
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        • 2012-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多