Name parser Write a program that prompts the user to input their full name (firs
ID: 3565762 • Letter: N
Question
- Name parser
- Write a program that prompts the user to input their full name (first, middle, and last) in one string. Use methods from the String class to split it up and output separate names, as well as a middle initial. Finally, the program should correctly detect when no middle name is entered. Test cases could include:
- "John Paul Jones" should state that "John" is the first name, "Paul" is the middle name, and "Jones" is the last name. It should then state that the middle initial is "P."
- "George Washington" should state that "George" is the first name, there is no middle name, and "Washington" is the last name. It should state that there is no middle initial.
Explanation / Answer
String name = "";
String fname,mName,lName;
List<String> splitNames = name.Split(' ').ToList();
if (splitNames.Count == 1)
fname = splitNames[0];
else if (splitNames.Count == 2)
{
fname = splitNames[0];
lName = splitNames[1];
}
else if (splitNames.Count == 3)
{
fname = splitNames[0];
lName = splitNames[2];
mName = splitNames[1].Substring(0,1);
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.