我收到全名,我需要将其分为称呼,名字和姓氏。
例如


史蒂夫·埃蒙德(Steve Emond)==>史蒂夫(Steve)为名,埃蒙德(Emond)为姓(此处称呼为空)
克里斯·巴克先生==>先生为称呼,克里斯为名,巴克为姓
贾斯汀==>贾斯汀为姓(Salutation和Firstname为空)


注意:收到Miss,Mr,Mrs作为称呼值。

码:

 String FirstName="";
 String fullName="Barker";
String[] nameArray=fullName.split(" ");
if(nameArray.length<3)
{
    System.out.println("Salutation: " + nameArray[0]);
    System.out.println("LastName: " + nameArray[1]);
    System.out.println("FirstName: " + FirstName);
}else if(nameArray.length>=3){
    System.out.println("Salutation: " + nameArray[0]);
    System.out.println("LastName: " + nameArray[nameArray.length - 1]);
    for (int index = 1; index < nameArray.length - 1; index++) {
        FirstName = FirstName + " " + nameArray[index];
     }
    System.out.println("FirstName: " + FirstName.trim());
}


当输入中给出的所有值(即Chris Barker先生)时,上面的代码都可以正常工作,在其余情况下,它会失败。谁能为我提供解决方案?

最佳答案

方法1:


    String fullName="Steve Emond";
		String[] nameArray=fullName.split(" ");
		if(nameArray.length==1)
		{
			System.out.println("LastName: " + nameArray[0]);

		}else if(nameArray.length==2){
			System.out.println("FirstName: " + nameArray[0]);
			System.out.println("LastName: " + nameArray[1]);
		}
		else if(nameArray.length==3){
			System.out.println("Salutation: " + nameArray[0]);
			System.out.println("FirstName: " + nameArray[1]);
			System.out.println("LastName: " + nameArray[2]);
		}





使用正则表达式方法2:



String fullName="Mr Justin raj Savarimuthu";
		Pattern pattern = Pattern.compile(new String ("(Mr\\s|Miss\\s|Mrs\\s)"));

		if(fullName.matches("(Mr\\s|Miss\\s|Mrs\\s).*"))
		{
			System.out.println("Salutation:"+fullName.substring(0,fullName.indexOf(' ')));
			fullName=pattern.split(fullName)[1].trim();
		}

		String[] parts = fullName.split(" ");
		String firstName="";
		for(int i=0;i<parts.length-1;i++)
		{
			firstName=firstName+parts[i]+" ";
		}
        if(firstName!="")
        	System.out.println("FirstName:"+firstName);
        System.out.println("LastName:"+parts[parts.length-1]);

关于java - 在Java中将全名拆分为Salutation,Firstname和lastname,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59820578/

10-10 00:58