使用字符作为扫描仪的起点和终点

时间:2014-09-13 18:21:58

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

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

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

我一直试图让扫描仪读取,直到它看到第一个' D'然后处理所有后面的数字,直到它到达第二个' D'下次扫描仪查找起点时,问题就出在第三个“D'

非常感谢任何帮助。

3 个答案:

答案 0 :(得分: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()一次。

答案 1 :(得分:0)

你甚至可以这样做

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
    }
}

答案 2 :(得分:0)

您有多种选择,以下是3:

1)使用Reader并检查每个角色:

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();
}