将第一个中间姓氏分开C#

时间:2017-07-29 05:01:47

标签: c# parsing names

目标:在用户输入名称时解析名称,并显示带有第一个中间名和姓氏的消息框。现在它只有当你输入三个名字时才有效,如果你试了两个名字就崩溃了,我确定它是我的阵列的原因但是我不知道我错在哪里。超级新手,我自己学习,所以任何帮助将不胜感激!!

P.S。用户看到的GUI只是一个输入块,用于将它们的名称输入一行,每个单词之间的间距。

 private void btnParseName_Click(object sender, System.EventArgs e)
    {
        string fullName = txtFullName.Text;
        fullName = fullName.Trim();

        string[] names = fullName.Split(' ');

        string firstName = "";
        string firstLetter = "";
        string otherFirstLetters = "";
        if (names[0].Length > 0)
        {
            firstName = names[0];
            firstLetter = firstName.Substring(0, 1).ToUpper();
            otherFirstLetters = firstName.Substring(1).ToLower();
        }

        string secondName = "";
        string secondFirstLetter = "";
        string secondOtherLetters = "";
        if (names[1].Length > 0)
         {
            secondName = names[1];
            secondFirstLetter = secondName.Substring(0, 1).ToUpper();
            secondOtherLetters = secondName.Substring(0).ToLower();
         }

        string thirdName = "";
        string thirdFirstLetter = "";
        string thirdOtherLetters = "";
        if (names[2].Length > 0)
        {

            thirdName = names[2];
            thirdFirstLetter = thirdName.Substring(0, 1).ToUpper();
            thirdOtherLetters = thirdName.Substring(0).ToLower();

        }

        MessageBox.Show(
                "First Name:         " + firstLetter + otherFirstLetters + "\n\n" +
                "Middle Name:        " + secondFirstLetter + secondOtherLetters + "\n\n" +
                "Last Name:          " + thirdFirstLetter + thirdOtherLetters);

4 个答案:

答案 0 :(得分:3)

以下是如何做到的工作示例:

public class FullName
{
    public  string FirstName { get; set; }
    public  string MiddleName { get; set; }
    public  string LastName { get; set; }

    public FullName()
    {

    }

    public FullName(string fullName)
    {
        var nameParts = fullName.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);

        if (nameParts == null)
        {
            return;
        }
        if (nameParts.Length > 0)
        {
            FirstName = nameParts[0];
        }
        if (nameParts.Length > 1)
        {
            MiddleName = nameParts[1];
        }
        if (nameParts.Length > 2)
        {
            LastName = nameParts[2];
        }
    }

    public override string ToString()
    {
        return $"{FirstName} {MiddleName} {LastName}".TrimEnd();
    }
}

用法示例:

class Program
{
    static void Main(string[] args)
    {
        var fullName = new FullName("first middle last");
        Console.WriteLine(fullName);
        Console.ReadLine();
    }
}

答案 1 :(得分:2)

您需要检查并处理第二个名称为空。初始化字符串将防止崩溃,然后检查输入。

string secondName = "";    
string secondFirstLetter = ""; 
string secondOtherLetters = "";

if(names.Length > 2)
{
    secondName = names[1];
    secondFirstLetter = secondName.Substring(0, 1).ToUpper();
    secondOtherLetters = secondName.Substring(0).ToLower();
}

事实上,值得初始化所有变量或管理用户输入验证。

答案 2 :(得分:0)

如另一个答案中所述,只有在存在第三个名称时才需要指定中间名 以下方法使用Dictionary.TryGetValue方法和C#7功能用于out参数。

var textInfo = System.Globalization.CultureInfo.CurrentCulture.TextInfo;
var names = fullName.Split(' ')
                    .Where(name => string.IsNullOrWhiteSpace(name) == false)
                    .Select(textInfo.ToTitleCase)
                    .Select((Name, Index) => new { Name, Index })
                    .ToDictionary(item => item.Index, item => item.Name);

names.TryGetValue(0, out string firstName);
names.TryGetValue(1, out string middleName);
if (names.TryGetValue(2, out string lastName) == false)
{
    lastName = middleName;
    middleName = null;
}

// Display result
var result = new StringBuilder();
result.AppendLine("First name: ${firstName}");
result.AppendLine("Middle name: ${middleName}");
result.AppendLine("Last name: ${lastName}");

MessageBox.Show(result.ToString());

答案 3 :(得分:0)

我知道您的问题已得到解答,您可以通过多种方式处理此问题,但这是我的建议,并在此过程中提供了一些解释:

private void button1_Click(object sender, EventArgs e)
{
    string fullName = "Jean Claude Van Dam";
    fullName = fullName.Trim();

    // So we split it down into tokens, using " " as the delimiter
    string[] names = fullName.Split(' ');

    string strFormattedMessage = "";

    // How many tokens?
    int iNumTokens = names.Length;

    // Iterate tokens
    for(int iToken = 0; iToken < iNumTokens; iToken++)
    {
        // We know the token will be at least one letter
        strFormattedMessage += Char.ToUpper(names[iToken][0]);

        // We can't assume there is more letters (they might have used an initial)
        if(names[iToken].Length > 1)
        {
            // Add them (make it lowercase)
            strFormattedMessage += names[iToken].Substring(1).ToLower();

            // Don't need to add "\n\n" for the last token
            if(iToken < iNumTokens-1)
                strFormattedMessage += "\n\n";
        }

        // Note, this does not take in to account names with hyphens or names like McDonald. They would need further examination.
    }

    if(strFormattedMessage != "")
    {
        MessageBox.Show(strFormattedMessage);
    }
}

此示例避免了所有变量。它使用operator []

希望这对你有帮助......:)