public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
在上面的代码中,我不想要中间名。我想从用户那里得到全名,然后它必须像firstname和lastname一样分开。
答案 0 :(得分:2)
您可以尝试String split
方法来执行此操作:
String name = "John King IV. Cena";
String []nameArray=name.split("\\s+");
System.out.println("FirstName "+nameArray[0] );
System.out.println("LastName "+nameArray[nameArray.length-1]);