'A string that must be exactly one name and another that must be exactly zero or one name
I have a code below where the first and last name strings have to be exactly one name and the middle name must be exactly zero or one name.. Do any of you guys in here have any idea how to do this? Thank you in advance!
public enum Gendertype { Male, Female };
public class Player
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Nationality { get; set; }
public string ShortNationality { get; set; }
public Gendertype Gender { get; set; }
public Player(string fn, string mn, string ln, DateTime dob, string n, string sn, Gendertype g)
{
FirstName = fn;
MiddleName = mn;
LastName = ln;
DateOfBirth = dob;
Nationality = n;
ShortNationality = sn;
Gender = g;
}
}
class Program
{
static void Main()
{
Player person1 = new Player("Rafael" + "\n", "" + "\n", "Nadal" + "\n", new DateTime(1986, 06, 03), "Spanish" + "\n", "ES" + "\n", Gendertype.Male);
Console.WriteLine("Player 1: \n First name = {0} Middle name = {1 } Last name = {2} Date of birth = {3:yyyy/MM/dd} \n Nationality = {4} Short name nationality = {5} Gender = {6}", person1.FirstName, person1.MiddleName, person1.LastName, person1.DateOfBirth, person1.Nationality, person1.ShortNationality, person1.Gender);
//Nedenstående aldersudregner er taget fra Bob Tabors C# kurser
DateTime DateOfBirth = DateTime.Parse("1986/06/03");
TimeSpan myAge = DateTime.Now.Subtract(DateOfBirth);
Console.WriteLine(" Age = " + myAge.TotalDays / 365 + "\n" + "\n");
Solution 1:[1]
For FirstName and LastName you can split on ' ' and see that the count is 1.
bool valid = fn.Split(' ').Length == 1
And for the MiddleName let it be also null or empty:
bool valid = string.InNullOrEmpty(mn) || mn.Split(' ').Length == 1
You can add .Trim if you think a space slipped into one of the names in the beginning or end.
bool validFN = fn.Trim().Split(' ').Length == 1
bool validMN = string.InNullOrEmpty(mn) || mn.Trim().Split(' ').Length == 1
Solution 2:[2]
Use String.Split for this:
var names = "Rafael Nadal".Split();
foreName = names[0];
if(names.Length == 2)
{
surName = names[1];
}
else if (names.Length == 3)
{
surName = names[2];
middleName = names[1];
}
else
throw new ArgumentException("Wrong number of arguments");
However if your input is delimited by another character such as a comma, you have to use the overload of Split that expects a character as parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | marc_s |
