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

This solution will work for people that have a last name that has more than one word. Treat the first word as the first name and leave everything else as the last name.

public static string getLastNameCommaFirstName(String fullName) {
    List<string> names = fullName.Split(' ').ToList();
    string firstName = names.First();
    names.RemoveAt(0);

    return String.Join(" ", names.ToArray()) + ", " + firstName;            
} 

For Example passing Brian De Palma into the above function will return "De Palma, Brian"

getLastNameFirst("Brian De Palma");
//returns "De Palma, Brian"

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.


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".