Search code examples
c#parsingnames

separate first middle last name C#


Goal: parse name when user enters name, and have a message box display with first middle and last name. Right now it only works when you type in three names, if you try two it crashes, and I'm sure it's cause of my array but Im not sure where I'm wrong. Super novice, learning on my own so any help would be greatly appreciated!!

P.S. GUI the user sees is just an entry block for them to enter their name into one line, spacing between each word.

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

Solution

  • You need to check for and handle the second name being empty. Initialising the string will prevent the crash, then checking for input.

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

    In fact it would be worth intialising all your variables or managing user input validation.