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();
}
}
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With