Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

android

I have a form with a full-name EditText field 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?

If user enter his/her name like A B C . First name will be A & Last Name Will 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();


    }

}
like image 290
IntelliJ Amiya Avatar asked May 18 '14 05:05

IntelliJ Amiya


2 Answers

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"

like image 161
Faakhir Avatar answered Nov 01 '22 17:11

Faakhir


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

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

like image 21
Ani Fichadia Avatar answered Nov 01 '22 16:11

Ani Fichadia