如何将全名字符串分成名字和姓氏字符串?

发布于 2024-11-19 07:06:21 字数 50 浏览 2 评论 0原文

我需要一些帮助,我有一个全名字符串,我需要做的是单独使用这个全名字符串作为名字和姓氏。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

你怎么敢 2024-11-26 07:06:22

这是我的扩展。它返回最后一个单词作为姓氏,其余单词作为名字。

public static void SplitFullName(this string fullName, out string firstName, out string lastName)
{
    firstName = string.Empty;
    lastName = string.Empty;
    if (!string.IsNullOrEmpty(fullName))
    {

        lastName = string.Empty; firstName = string.Empty;
        int splitIndex = fullName.LastIndexOf(' ');
        if (splitIndex >= 0)
        {
            firstName = fullName.Substring(0, splitIndex);
            lastName = fullName.Substring(splitIndex + 1);
        }
        else
            firstName = fullName;
    }

}

用法:

"Micheal".SplitFullName(out string first, out string last);
// first = "Micheal"
// last = ""

"Micheal Jackson".SplitFullName(out string first, out string last);
// first = "Micheal"
// last = "Jackson"

"Micheal Joseph Jackson".SplitFullName(out string first, out string last);
// first = "Micheal Joseph"
// last = "Jackson"

顺便说一句,Visual Studio Intellisense 正在失控!我只编写了 if 条件的代码,其余的由 Intellisense 完成。

Here is my extension. It returns the last word as the last name and the rest as the first name.

public static void SplitFullName(this string fullName, out string firstName, out string lastName)
{
    firstName = string.Empty;
    lastName = string.Empty;
    if (!string.IsNullOrEmpty(fullName))
    {

        lastName = string.Empty; firstName = string.Empty;
        int splitIndex = fullName.LastIndexOf(' ');
        if (splitIndex >= 0)
        {
            firstName = fullName.Substring(0, splitIndex);
            lastName = fullName.Substring(splitIndex + 1);
        }
        else
            firstName = fullName;
    }

}

Usage:

"Micheal".SplitFullName(out string first, out string last);
// first = "Micheal"
// last = ""

"Micheal Jackson".SplitFullName(out string first, out string last);
// first = "Micheal"
// last = "Jackson"

"Micheal Joseph Jackson".SplitFullName(out string first, out string last);
// first = "Micheal Joseph"
// last = "Jackson"

On a side note Visual Studio Intellisense is getting out of hand! I only wrote the code up to the if condition and the rest was completed by Intellisense.

没企图 2024-11-26 07:06:22

dart/flutter 中的解决方案:

var fullName = 'Jawad Hussain Abbasi';

firstName = fullName.split(' ')[0];

lastName = fullName.split(' ').skip(1).join(" ");

log('First Name: $firstName'); // Jawad

log('Last Name: $lastName'); // Hussain Abbasi

Solution in dart/flutter:

var fullName = 'Jawad Hussain Abbasi';

firstName = fullName.split(' ')[0];

lastName = fullName.split(' ').skip(1).join(" ");

log('First Name: $firstName'); // Jawad

log('Last Name: $lastName'); // Hussain Abbasi
热情消退 2024-11-26 07:06:21

如果您确定自己有名字和姓氏,这将起作用。

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

确保检查名称的长度。

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

更新

当然,这是对问题的相当简化的看法。我的回答的目的是解释 string.Split() 的工作原理。但是,您必须记住,有些姓氏是复合名,例如 @AlbertEin 指出的“Luis da Silva”。

这远不是一个简单就能解决的问题。一些介词(法语、西班牙语、葡萄牙语等)是姓氏的一部分。这就是为什么@John Saunders 问“什么语言?”。 John 还指出,前缀(Mr.、Mrs.)和后缀(Jr.、III、MD)可能会造成妨碍。

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.

独自唱情﹋歌 2024-11-26 07:06:21

您可以尝试使用空格来解析它,但它不会起作用,示例:

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

但是如果有大量用户输入,这会失败,如果他确实有两个名字怎么办? “胡安·巴勃罗·佩雷斯”。

名称很复杂,因此不可能始终知道给定字符串中名字和姓氏的哪一部分。

编辑

您不应该使用 string.Split 方法来提取姓氏,有些姓氏是由两个或多个单词组成的,例如我的一个朋友的姓氏是“Ponce de Leon”。

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

离不开的别离 2024-11-26 07:06:21

此解决方案适用于姓氏包含多个单词的人。将第一个单词视为名字,将其他所有内容视为姓氏。

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;            
} 

例如,将 Brian De Palma 传递到上述函数中将返回“De Palma, Brian”

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

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"
与酒说心事 2024-11-26 07:06:21

您可以使用此版本 (MSDN)< Split 方法的 /strong> 如下:

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

在这种情况下,split[0] 将是 Johnsplit[ 1]将是Deo。另一个例子:

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

在这种情况下,split[0] 将是 Johnsplit[1] 将是 Wesley Doe

请注意,split 的长度永远不会超过 2

因此,通过以下代码,您可以很好地获得 FirstNameLastName

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];
}

希望这个答案为本页面添加一些有用的内容。

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.

八巷 2024-11-26 07:06:21

尝试:

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

Try:

  string fullName = "The mask lol"; 
    string[] names = fullName.Split(' '); 
    string name = names.First();
    string lasName = names.Last(); 
じее 2024-11-26 07:06:21

我建议使用 Regex 来严格定义您的名字和姓氏。

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

家住魔仙堡 2024-11-26 07:06:21

nuget 有多种名称解析/拆分的实现。如果您深入研究 NameParserSharp 存储库,您还可以组合两个部分类并复制并复制它。粘贴到您自己的库中。

NameParserSharp

更多内容请参见 Nuget

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

所有深爱都是秘密 2024-11-26 07:06:21

name =“托尼·斯塔克死了”;

get_first_name(String name) {
    var names = name.split(' ');
    String first_name= "";
 
    for (int i = 0; i != names.length; i++) {
      if (i != names.length - 1) 
      {
        if (i == 0) {
          first_name= first_name+ names[i];
        } else {
          first_name= first_name+ " " + names[i];
        }
      }
    }
    return first_name; // Tony Stark is
  }



  get_last_name(String name) {
    var names = name.split(' ');
    return names[names.length - 1].toString(); // dead
  }

name ="Tony Stark is dead";

get_first_name(String name) {
    var names = name.split(' ');
    String first_name= "";
 
    for (int i = 0; i != names.length; i++) {
      if (i != names.length - 1) 
      {
        if (i == 0) {
          first_name= first_name+ names[i];
        } else {
          first_name= first_name+ " " + names[i];
        }
      }
    }
    return first_name; // Tony Stark is
  }



  get_last_name(String name) {
    var names = name.split(' ');
    return names[names.length - 1].toString(); // dead
  }
谜兔 2024-11-26 07:06:21

这是我在项目中使用的一段 C# 代码。它返回最后一个单词作为姓氏,其余单词作为名字。

Fiddle

输出:

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

PS 抱歉,没有中间名。

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;
}

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;
}
难如初 2024-11-26 07:06:21

这就像调用 string.Split() 一样简单吗,传递一个空格作为分割字符?或者这里发生了什么更棘手的事情? (如果是后者,请用更多信息更新您的问题。)

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

动次打次papapa 2024-11-26 07:06:21

对于基本用例,很容易将其拆分为“ ”或“,”,但是由于名称多种多样,其中包含不同的内容,这并不总是有效。

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.

ι不睡觉的鱼゛ 2024-11-26 07:06:21

所以如果你把第一个空格作为名字,其余的作为姓氏,这会给我们

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;
}

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;
}
木森分化 2024-11-26 07:06:21

简单的代码可以将Flowers, Love等内容转换为Love Flowers(这适用于非常复杂的名称,例如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() + " "}");
        } 

输出:爱花

相反。爱花转换为花,爱:

        string fullname = "Love Flowers";
        int indexOfTheSpace = fullname.IndexOf(' ');
        string firstname = fullname.Substring(0, indexOfTheSpace);
        string lastname = fullname.Substring(indexOfTheSpace + 1);
        WriteLine($"{lastname}, {firstname}");

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}");
下雨或天晴 2024-11-26 07:06:21

有不止一种方法可以实现这一点。我的具体情况通过如下代码示例解决。

例如


如果用户名中只有一个空格。

 int idx = fullName.IndexOf(' '); //This customer name : Osman Veli

如果用户名中存在多个空格。

 if (fullName.Count(Char.IsWhiteSpace) > 1)
 {
    idx = fullName.LastIndexOf(' '); //This customer name : Osman Veli Sağlam
 }

  if (idx != -1)
  {
    // Osman Veli Sağlam
    firstName = fullName.Substring(0, idx); // FirstName: Osman Veli 
    lastName = fullName.Substring(idx + 1); // LastName : Sağlam
   }

There is more than one method for this. My specific situation is solved with a code example like below.

for Example


if there is only one space in the user's name.

 int idx = fullName.IndexOf(' '); //This customer name : Osman Veli

if there is more than one space in the user's name.

 if (fullName.Count(Char.IsWhiteSpace) > 1)
 {
    idx = fullName.LastIndexOf(' '); //This customer name : Osman Veli Sağlam
 }

  if (idx != -1)
  {
    // Osman Veli Sağlam
    firstName = fullName.Substring(0, idx); // FirstName: Osman Veli 
    lastName = fullName.Substring(idx + 1); // LastName : Sağlam
   }
娇柔作态 2024-11-26 07:06:21

您可以创建一个值对象来表示名称并在应用程序中使用它

public class Name
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public string FullName { get; }

    public Name(string name)
    {
        if (string.IsNullOrEmpty(name))
            return;

        FullName = name;

        LoadFirstAndLastName();
    }

    private void LoadFirstAndLastName()
    {
        var names = FullName.Trim().Split(" ", 2);

        FirstName = names.First();

        if (names.Count() > 1)
            LastName = names.Last();
    }

    public override string ToString() => FullName;

    //Enables implicit set (Name name = "Rafael Silva")
    public static implicit operator Name(string name) => new Name(name);
}

Name name = "Jhon Doe"; //FirstName = Jhon - LastName = Doe
Name name = new Name("Jhon Doe"); //FirstName = Jhon - LastName = Doe    
Name name = new Name("Rafael Cristiano da Silva"); //FirstName = Rafael - LastName = Cristiano da Silva

//On class property
public Name Name {get; set; } = "Jhon Doe";

you can create a value object to represent a name and use it in your application

public class Name
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public string FullName { get; }

    public Name(string name)
    {
        if (string.IsNullOrEmpty(name))
            return;

        FullName = name;

        LoadFirstAndLastName();
    }

    private void LoadFirstAndLastName()
    {
        var names = FullName.Trim().Split(" ", 2);

        FirstName = names.First();

        if (names.Count() > 1)
            LastName = names.Last();
    }

    public override string ToString() => FullName;

    //Enables implicit set (Name name = "Rafael Silva")
    public static implicit operator Name(string name) => new Name(name);
}

Usages:

Name name = "Jhon Doe"; //FirstName = Jhon - LastName = Doe
Name name = new Name("Jhon Doe"); //FirstName = Jhon - LastName = Doe    
Name name = new Name("Rafael Cristiano da Silva"); //FirstName = Rafael - LastName = Cristiano da Silva

//On class property
public Name Name {get; set; } = "Jhon Doe";
我偏爱纯白色 2024-11-26 07:06:21

迟到总比不到好,这是我在许多应用程序中使用的解决方案。

 string fullName = "John De Silva";
 string[] names = fullName.Split(" ");
 string firstName = names.First(); // John
 string lastName = string.Join(" ", names.Skip(1).ToArray()); // De Silva

享受 !

Better to be late than never, here is my solution for this used in many applications.

 string fullName = "John De Silva";
 string[] names = fullName.Split(" ");
 string firstName = names.First(); // John
 string lastName = string.Join(" ", names.Skip(1).ToArray()); // De Silva

Enjoy !

梦途 2024-11-26 07:06:21
Sub SplitFullName(Full_Name As String)

        Dim names = Full_Name.Split(" ")
        Dim FirstName As String = ""
        Dim MiddletName As String = ""
        Dim LastName As String = ""
        If names.Count = 0 Then
            FirstName = ""
            MiddletName = ""
            LastName = ""
        ElseIf names.Count = 1 Then
            FirstName = names(0)
        ElseIf names.Count = 2 Then
            FirstName = names(0)
            LastName = names(1)
        Else
            FirstName = names(0)
            For i = 1 To names.Count - 2
                MiddletName += " " & names(i)
            Next
            LastName = names(names.Count - 1)
        End If
        MsgBox("The first name is: " & FirstName & ";   The middle name is: " & MiddletName & ";    The last name is: " & LastName)

End Sub
Sub SplitFullName(Full_Name As String)

        Dim names = Full_Name.Split(" ")
        Dim FirstName As String = ""
        Dim MiddletName As String = ""
        Dim LastName As String = ""
        If names.Count = 0 Then
            FirstName = ""
            MiddletName = ""
            LastName = ""
        ElseIf names.Count = 1 Then
            FirstName = names(0)
        ElseIf names.Count = 2 Then
            FirstName = names(0)
            LastName = names(1)
        Else
            FirstName = names(0)
            For i = 1 To names.Count - 2
                MiddletName += " " & names(i)
            Next
            LastName = names(names.Count - 1)
        End If
        MsgBox("The first name is: " & FirstName & ";   The middle name is: " & MiddletName & ";    The last name is: " & LastName)

End Sub
仅此而已 2024-11-26 07:06:21

我添加了更多检查以获得所需的结果
例如,其他解决方案有效,但当我故意占用两个空格时,它不起作用,所以这里是解决方法。

final name = ' sambhav';
final words = name.trim().split(' ');
final firstName = words[0];
final lastName = words.length > 1 ? words[words.length - 1] : '';
print('first name : $firstName, last name : $lastName');

结果

input : Sambhav jain // first name : Sambhav, last name : jain    
input : Sambhav the jain // first name : Sambhav, last name : jain  
input : Sambhav // first name : Sambhav, last name :

I've added some more check to get the desired result
for example other solution work but when i intentionally take two spaces it do not work, so here is workaround.

final name = ' sambhav';
final words = name.trim().split(' ');
final firstName = words[0];
final lastName = words.length > 1 ? words[words.length - 1] : '';
print('first name : $firstName, last name : $lastName');

Result

input : Sambhav jain // first name : Sambhav, last name : jain    
input : Sambhav the jain // first name : Sambhav, last name : jain  
input : Sambhav // first name : Sambhav, last name :
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文