如何从 Android 中的全名拆分名字和姓氏字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23718977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:22:41  来源:igfitidea点击:

How To Split First & Last Name String From Full Name In Android

androidstring

提问by IntelliJ Amiya

I have a form with a full-name EditTextfield and I would like to break the string into a first and last name strings . Can any one help me on this? May I know what is the correct way to achieve my objective?

我有一个带有全名字EditText段的表单,我想将字符串分成名字和姓氏字符串。谁可以帮我这个事?我可以知道实现目标的正确方法是什么吗?

If user enter his/her name like A B C. First name will be A& Last Name Will BC

如果用户输入他/她的名字,如A B C。名字将是A和姓氏将BC

I am trying This :

我正在尝试这个:

EditText UNSP =(EditText)findViewById(R.id.UserNameToSIGNUP);
    String UserFullName=UNSP.getText().toString();

    String[] arr=UserFullName.split(" ");

    String fname=arr[0];
    String lname=arr[1];

    Log.d("First name",fname);
    Log.d("last name",lname);



    if(UserFullName.length()==0) {

        Toast.makeText(getApplicationContext(), "Submit Name", Toast.LENGTH_SHORT).show();
    }

    else{

         Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();


    }

}

回答by Faakhir

In case you need only last and first name from full name without using array this is best approach in my point of view. First name can be on two or more than two words but last name always on one word in real world.

如果您只需要全名中的姓氏和名字而不使用数组,这是我认为的最佳方法。名字可以在两个或两个以上的词上,但在现实世界中姓氏总是在一个词上。

    String name = "Abdul Latif Hussain"
    String lastName = "";
    String firstName= "";
    if(name.split("\w+").length>1){

       lastName = name.substring(name.lastIndexOf(" ")+1);
       firstName = name.substring(0, name.lastIndexOf(' '));
    }
     else{
       firstName = name;
    }

Output String will be: firstName= "Abdul Latif" lastName = "Hussain"

输出字符串将是: firstName="Abdul Latif" lastName="Hussain"

回答by Ani Fichadia

For multiple names, it's better to just have separate EditTextsfor each field.

对于多个名称,最好将EditTexts每个字段分开。

For your implementation, If you can guarantee that they enter it in that format, you can just go:

对于您的实施,如果您可以保证他们以该格式输入,您可以去:

int firstSpace = UserFullName.indexOf(" "); // detect the first space character
String firstName = UserFullName.substring(0, firstSpace);  // get everything upto the first space character
String lastName = UserFullName.substring(firstSpace).trim(); // get everything after the first space, trimming the spaces off

just put some error checking to ensure the format is right, otherwise you may get exceptions

只需进行一些错误检查以确保格式正确,否则可能会出现异常

回答by Bharath Kumar Bachina

Please use this. It will work 100%

请使用这个。它将工作 100%

str = UNSP.getText().toString();
String[] splited = str.split("\s+");

回答by Fco P.

It's easier to use String.split(" ").This will create separated strings, each one ending when the " "char is found.

更容易使用String.split(" ").这将创建分隔的字符串,每个字符串在" "找到字符时结束。

回答by HixField

In Kotlin, I came up with the following solution:

在 Kotlin 中,我想出了以下解决方案:

val displayName = "John Smith Fidgerold Trump"
var parts  = displayName.split(" ").toMutableList()
val firstName = parts.firstOrNull()
parts.removeAt(0)
val lastName = parts.joinToString(" ")
Log.debug("*** displayName: $displayName")
Log.debug("*** firsteName : $firstName")
Log.debug("*** lastName : $lastName")
Log.debug("**************")    

Sample output:

示例输出:

> ** displayName: John Smith Fidgerold Trump
> ** firsteName : John
> ** lastName   : Smith Fidgerold Trump
> *************
> ** displayName: John Smith Fidgerold
> ** firsteName : John
> ** lastName   : Smith Fidgerold
> *************
> ** displayName: John Smith
> ** firsteName : John
> ** lastName   : Smith
> *************
> ** displayName: John
> ** firsteName : John
> ** lastName   : 
> *************
> ** displayName: 
> ** firsteName : 
> ** lastName   : 
> *************

回答by Emre Aydemir

For only first name:

仅用于名字:

 public static void getUserFirstName(String fullname){
    String firstName;
    String[] fullNameArray = fullname.split("\s+");
    if(fullNameArray.length>1) {
        StringBuilder firstNameBuilder = new StringBuilder();
        for (int i = 0; i < fullNameArray.length - 1; i++) {
            firstNameBuilder.append(fullNameArray[i]);
            if(i != fullNameArray.length - 2){
                firstNameBuilder.append(" ");
            }
        }
        firstName = firstNameBuilder.toString();
    }
    else{
        firstName = fullNameArray[0];
    }
}

回答by Adriatik Gashi

Kotlinversion:

科特林版本:

val fullName = "Adriatik Gashi"
val idx = fullName.lastIndexOf(' ')
if (idx == -1) {
      Toast.makeText(context, "Invalid full name", Toast.LENGTH_LONG).show()
      return
}

val firstName = fullName.substring(0, idx)
val lastName = fullName.substring(idx + 1)
Log.e("SPLITED NAME", firstName + " - " + lastName)