使用useDelimiter()连接子串 [英] Using useDelimiter() to join substrings
问题描述
我的方法 readDataFromFile()
可以读取如下文本文件:
My method readDataFromFile()
can read text files like:
Bird Golden Eagle Eddie
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
第一列是动物的'Type',第二列是'Species',第三列是'Name'。
The first column is the 'Type' of animal, second column is 'Species' and third is 'Name'.
当前输出:
Bird Golden Eagle < (Golden and Eagle count as different substrings).
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
- 我如何使用
useDelimiter
方法将金鹰算作一个品种? - How would I use the
useDelimiter
method to make 'Golden Eagle' count as one species?
当前代码:
while(scanner.hasNextLine())
{
String type = scanner.next();
String species = scanner.next();
String name = scanner.next();
System.out.println(type + " " + species + " " + name);
scanner.nextLine();
addAnimal( new Animal(species, name, this) );
}
推荐答案
第一行的'Golden Eagle'都用标签分隔
the first line has 'Golden Eagle' both separated by a tab
这是不对的。
您的问题来源显示了这些列全部由制表符分隔( \t
又名 \ u0009
),但 Golden
和 Eagle
由 space 字符分隔( \ u0020
)。
The source of your question shows that the columns are all separated by a tab character (\t
aka \u0009
), but Golden
and Eagle
are separated by a space character (\u0020
).
请勿使用扫描程序
读取文件。它非常慢,不适合解析文件。相反,使用 BufferedReader
和 readline()
方法,然后 split()
列成行。
Do not read your file using Scanner
. It is very slow and not the appropriate tool for parsing your file. Instead, use a BufferedReader
and the readline()
method, then split()
the line into columns.
演示
try (BufferedReader in = Files.newBufferedReader(Paths.get("animals.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
String[] values = line.split("\t");
for (String value : values)
System.out.printf("%-15s", value);
System.out.println();
}
}
输出
Bird Golden Eagle Eddie
Mammal Tiger Tommy
Mammal Lion Leo
Bird Parrot Polly
Reptile Cobra Colin
如你所见,金鹰
文字未被分割。
As you can see, the Golden Eagle
text did not get split.
这篇关于使用useDelimiter()连接子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!