3

Scannerクラスを使用して、next(Pattern pattern)メソッドを使用して行を読み取り、コロンの前とコロンの後にテキストをキャプチャして、s1=textbeforecolonおよびs2=textaftercolonとなるようにしようとしています。

行は次のようになります。

何か:何か他

4

3 に答える 3

10

これを行うには、具体的に何が必要かによって、2つの方法があります。

useDelimiter()入力全体をコロンで分割する場合は、他の人が指摘しているように、このメソッドを使用できます。

// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");

// Examines each token one at a time
while (scanner.hasNext())
{
    String token = scanner.next();
    // Do something with token here...
}

各行をコロンで分割する場合は、Stringsplit()メソッドを使用する方がはるかに簡単です。

while (scanner.hasNextLine())
{
    String[] parts = scanner.nextLine().split(":");
    // The parts array now contains ["something", "somethingelse"]
}
于 2009-05-09T03:03:06.697 に答える
0

スキャナーでPatternを使用したことはありません。

私はいつも文字列でデリメータを変更しました。 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)

于 2009-05-09T02:49:53.140 に答える
0
File file = new File("someFileWithLinesContainingYourExampleText.txt");
Scanner s = new Scanner(file);
s.useDelimiter(":");

while (!s.hasNextLine()) {
    while (s.hasNext()) {
        String text = s.next();
    System.out.println(text);
    }

    s.nextLine();
}
于 2009-05-09T02:50:22.763 に答える