Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate full name string into firstname and lastname string?

I need some help with this, I have a fullname string and what I need to do is separate and use this fullname string as firstname and lastname separately.

like image 677
user773456 Avatar asked Jul 08 '11 18:07

user773456


People also ask

How do you split first name middle name and last name in Python?

split() print(f"{first}, {middle[0] if middle else ''}, {last}") Using the packing operator * for the second variable name will place any remaining values (names) into a list by the name 'middle'.


2 Answers

This will work if you are sure you have a first name and a last name.

string fullName = "Adrian Rules"; var names = fullName.Split(' '); string firstName = names[0]; string lastName = names[1]; 

Make sure you check for the length of names.

names.Length == 0 //will not happen, even for empty string names.Length == 1 //only first name provided (or blank) names.Length == 2 //first and last names provided names.Length > 2 //first item is the first name. last item is the last name. Everything else are middle names 

Update

Of course, this is a rather simplified view on the problem. The objective of my answer is to explain how string.Split() works. However, you must keep in mind that some last names are composite names, like "Luis da Silva", as noted by @AlbertEin.

This is far from being a simple problem to solve. Some prepositions (in french, spanish, portuguese, etc.) are part of the last name. That's why @John Saunders asked "what language?". John also noted that prefixes (Mr., Mrs.) and suffixes (Jr., III, M.D.) might get in the way.

like image 170
Adriano Carneiro Avatar answered Sep 18 '22 13:09

Adriano Carneiro


You could try to parse it using spaces but it's not going to work, Example:

var fullName = "Juan Perez"; var name = fullName.Substring(0, fullName.IndexOf(" ")); var lastName = fullName.Substring(fullName.IndexOf(" ") + 1); 

But that would fail with a ton of user input, what about if he does have two names? "Juan Pablo Perez".

Names are complicated things, so, it's not possible to always know what part is the first and last name in a given string.

EDIT

You should not use string.Split method to extract the last name, some last names are composed from two or more words, as example, a friend of mine's last name is "Ponce de Leon".

like image 23
albertein Avatar answered Sep 17 '22 13:09

albertein