一个字符串,必须是一个名称,另一个必须是零或一个名称

时间:2017-04-23 12:13:46

标签: c#

我在下面有一个代码,其中第一个和最后一个名称字符串必须是一个名称,中间名称必须正好是零或一个名称..你们这里的任何人都知道如何做到这一点吗?先感谢您!

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

2 个答案:

答案 0 :(得分:0)

对于FirstNameLastName,您可以在' '上拆分并查看计数为1。

bool valid = fn.Split(' ').Length == 1

对于MiddleName,让它也为空或空:

bool valid = string.InNullOrEmpty(mn) || mn.Split(' ').Length == 1

如果您认为某个空格在开头或结尾的某个名称中滑落,则可以添加.Trim

bool validFN = fn.Trim().Split(' ').Length == 1
bool validMN = string.InNullOrEmpty(mn) || mn.Trim().Split(' ').Length == 1

答案 1 :(得分:0)

使用var messages = ["%d zombies attack", "A boss with %d minions attacks"], // define your messages messageIndex = Math.floor(Math.random() * messages.length), // pick one of them numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message document.getElementById('quote').textContent = result;

String.Split

但是,如果您的输入由另一个字符(如逗号)分隔,则必须使用期望字符作为参数的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 ArgumetException("Whrong number of arguments"); 重载。