[英]Split string with three words
我的代碼現在看起來像這樣(有關更新的代碼,請參見下文):
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++;
}
這是完整的file.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;
}
}
我收到多個錯誤,怎么了?
假設每行總是恰好包含三個詞,而不是分裂,你可以簡單地使用Scanner
S分析next
各行三次。
Scanner scanner = new Scanner(new File("file.txt"));
int i = 0;
while (scanner.hasNextLine()) {
String first = scanner.next();
String second = scanner.next();
String last = scanner.next();
//System.out.println(first+": "+second+": "+last);
i++;
}
line.split("\\s+"); // don't use " ". use "\\s+" for more than one whitespace
假設該行有3個以上的單詞,請使用split(delimiter)
方法:
String line = ...;
String[] parts = line.split("\\s+"); // Assuming words are separated by whitespaces, use another if required
那么您可以分別訪問第一個,第二個和最后一個:
String first = parts[0];
String second = parts[1];
String last = parts[parts.length() - 1];
請記住,索引以0開頭。
String []parts=line.split("\\s+");
System.out.println(parts[0]);
System.out.println(parts[1]);
System.out.println(parts[parts.length-1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.