【发布时间】:2014-03-05 16:46:57
【问题描述】:
拆分包含三个单词的字符串的最佳方法是什么?
我的代码现在看起来像这样(更新代码见下文):
BufferedReader infile = new BufferedReader(new FileReader("file.txt"));
String line;
int i = 0;
while ((line = infile.readLine()) != null) {
String first, second, last;
//Split line into first, second and last (word)
//Do something with words (no help needed)
i++;
}
这是完整的文件.txt:
Allegrettho Albert 0111-27543 Brio Britta 0113-45771 Cresendo Crister 0111-27440 Dacapo Dan 0111-90519 Dolce Dolly 0116-31418 Espressivo Eskil 0116-19042 Fortissimo Folke 0118-37547 Galanto Gunnel 0112-61805 Glissando Gloria 0112-43918 Grazioso Grace 0112-43509 Hysterico Hilding 0119-71296 Interludio Inga 0116-22709 Jubilato Johan 0111-47678 Kverulando Kajsa 0119-34995 Legato Lasse 0116-26995 Majestoso Maja 0116-80308 Marcato Maria 0113-25788 Molto Maja 0117-91490 Nontroppo Maistro 0119-12663 Obligato Osvald 0112-75541 Parlando Palle 0112-84460 Piano Pia 0111-10729 Portato Putte 0112-61412 Presto Pelle 0113-54895 Ritardando Rita 0117-20295 Staccato Stina 0112-12107 Subito Sune 0111-37574 Tempo Kalle 0114-95968 Unisono Uno 0113-16714 Virtuoso Vilhelm 0114-10931 Xelerando Axel 0113-89124
@Pshemo 建议的新代码:
public String load() {
try {
Scanner scanner = new Scanner(new File("reg.txt"));
while (scanner.hasNextLine()) {
String firstname = scanner.next();
String lastname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
msg = "The file reg.txt has been opened";
return msg;
} catch (NumberFormatException ne) {
msg = ("Can't find reg.txt");
return msg;
} catch (IOException ie) {
msg = ("Can't find reg.txt");
return msg;
}
}
我收到多个错误,怎么了?
【问题讨论】:
-
您需要使用
String#split,但需要知道在哪里拆分字符串。 -
给出样本输入输出..分割的标准是什么?
-
你需要用
"\\s+"拆分。 -
您的代码(添加了
msg和list)在您提供的文件中对我来说很好用。可能问题出在其他地方。我建议使用完整但简化的代码mcve 和可用于重现您的问题的数据创建新问题。还要确保您的数据文件中确实没有空行(就像它的末尾一样)。 -
您可以将
scanner.hasNextLine()更改为scanner.hasNext()。您的代码的可读性会降低,但这样一来,如果真的有下一个(非空格)元素要读取,您就只能使用scanner.next()。此外,这仅适用于第一个元素 (firstname),因此如果行不包含三个元素,您将看到lastname或number的相同错误。