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

狂风中的少年 提交于 2019-11-28 05:23:44

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

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"

Try:

  string fullName = "The mask lol"; 
    string[] names = fullName.Split(' '); 
    string name = names.First();
    string lasName = names.Last(); 

You can use this version (MSDN) of Split method like follow:

var testcase = "John Doe";
var split = testcase.Split(new char[] { ' ' }, 2);

In this case split[0] will be John and split[1] will be Deo. another example:

var testcase = "John Wesley Doe";
var split = testcase.Split(new char[] { ' ' }, 2);

In this case split[0] will be John and split[1] will be Wesley Doe.

Notice that the length of split never be more than 2

So with following code you can get FirstName and LastName nicely:

var firstName = "";
var lastName = "";
var split = testcase.Split(new char[] { ' ' }, 2);
if (split.Length == 1)
{
    firstName = "";
    lastName = split[0];
}
else
{
    firstName = split[0];
    lastName = split[1];
}

Hope this answer add something useful to this page.

I would recommend using a Regex to rigorously define what your first and last names look like.

There are several implementations of name parsing/splitting over at nuget. If you dive into the NameParserSharp repository you can also just combine two partial classes and copy & paste into your own library.

NameParserSharp

More at Nuget

Here is a piece of c# code that I use on my projects. It returns the last word as surname and the rest as name.

Fiddle

Output:

Mary Isobel Catherine O’Brien
-------------------------
Name : Mary Isobel Catherine , Surname : O’Brien

P.S. No middle name, sorry.

public static string[] SplitFullNameIntoNameAndSurname(string pFullName)
{
    string[] NameSurname = new string[2];
    string[] NameSurnameTemp = pFullName.Split(' ');
    for (int i = 0; i < NameSurnameTemp.Length; i++)
    {
        if (i < NameSurnameTemp.Length - 1)
        {
            if (!string.IsNullOrEmpty(NameSurname[0]))
                NameSurname[0] += " " + NameSurnameTemp[i];
            else
                NameSurname[0] += NameSurnameTemp[i];
        }
        else
            NameSurname[1] = NameSurnameTemp[i];
    }
    return NameSurname;
}

Is this as simple as calling string.Split(), passing a single space as the split character? Or is there something trickier going on here? (If the latter, please update your question with more info.)

for basic use cases its easy to just split on ' ' or ', ' however due to the variety of names with differing things in them this is not going to always work.

Ggalla1779

So if you take the First space as Name and rest as Surname, this would give us

Person myPerson = new Person();

Misc tidyup = new Misc();
string[] result = tidyup.SplitFullName(tb1.Text);

foreach (string s in result)
{
    Console.WriteLine(s);

    if (result.First() == s)
    {
        myPerson.FirstName = s;
    }
    else
    {
        myPerson.LastName += s + " ";
        Console.WriteLine(s);
        Console.WriteLine(myPerson.LastName);
    }
}    

public string[] SplitFullName(string myName)
{
    string[] names = myName.Split(' ');
    //string firstName = names[0];
    //string lastName = names[1];

    return names;
}

Easy, simple code to transform something like Flowers, Love to Love Flowers (this works with very complex names such as Williams Jones, Rupert John):

        string fullname = "Flowers, Love";
        string[] fullnameArray = fullname.Split(",");//Split specify a separator character, so it's removed
        for (int i = fullnameArray.Length - 1; i >= fullnameArray.Length - 2; i--)
        {
                Write($"{fullnameArray[i].TrimStart() + " "}");
        } 

output: Love Flowers

The other way around. Love Flowers converted to Flowers, Love:

        string fullname = "Love Flowers";
        int indexOfTheSpace = fullname.IndexOf(' ');
        string firstname = fullname.Substring(0, indexOfTheSpace);
        string lastname = fullname.Substring(indexOfTheSpace + 1);
        WriteLine($"{lastname}, {firstname}");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!