我正在编写一个程序来限制输出中可以包含的字符数。基本上是学生ID分配者,我现在确定如何只计算字符串中特定数量的字符。到目前为止,我的代码看起来像这样。
string firstname, middleinitial, lastname,yearofentry;
int year;
Console.WriteLine("Please enter your first name.");
firstname = Console.ReadLine();
Console.WriteLine("Please enter your middle initial.");
middleinitial = Console.ReadLine();
Console.WriteLine("Please enter your last name.");
lastname = Console.ReadLine();
Console.WriteLine("Please enter your year of entry.");
yearofentry = Console.ReadLine();
year = (Convert.ToInt32(yearofentry)-2000);
Console.WriteLine(firstname +middleinitial+ lastname + year + "@mail.edu");
}
}
}
答案 0 :(得分:0)
只需读入完整字符串TrimStart(),然后使用Substring()获取所需的部分
Console.WriteLine("Please enter your last name.");
lastname = Console.ReadLine().TrimStart();
var substrLen = Math.Min(lastname.Length, 7);
lastname = lastname.Substring(0, substrLen);
在最后一次WriteLine()调用中,您可以使用.ToString(" 00")来获取您需要的2位数
Console.WriteLine(firstname + middleinitial + lastname + year.ToString("00") + "@mail.edu");
您应该检查您的用户是否输入了2000到2099之间的值。