
[英]How can I separate a string in Java from full name to last name, first name?
[英]how to split first and last name in string array in java
我有一個包含15個全名的數組,如何將其分成2個數組(名和姓),下面是我的全名數組的方法
public static void readData(String file) throws FileNotFoundException {
x = new Scanner(new File(file));
//count number of names in the array
int n = 0;
while(x.hasNextLine()) {
n++;
x.nextLine();
}
//open another scanner to avoid null
Scanner x1 = new Scanner(new File(file));
name = new String[n];
//get the array and print
for(int i = 0; i < name.length; i++ )
name[i] = x1.nextLine();
System.out.println(Arrays.toString(name));
}
文件包含15個全名,如下所示:
Max Frei
Stephen King
Agatha Christie
如何閱讀:
final int total = 15;
String[] firstNames = new String[total];
String[] lastNames = new String[total];
try (Scanner scan = new Scanner(new File("file"))) {
for (int i = 0; i < total; i++) {
firstNames[i] = scan.next();
lastNames[i] = scan.next();
}
}
// firstNames: Max, Stephen, Agatha
// lastNames: Frei, King, Christie
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.