[英]How do I limit the number of characters that can be in a string?
I'm writing a program that limits how many characters can be in the output. 我正在编写一个程序来限制输出中可以包含的字符数。 Essentially a student id assigner and I'm now sure how to count only a specific amount of characters in a string.
基本上是学生ID分配者,我现在确定如何只计算字符串中特定数量的字符。 My code looks like this so far.
到目前为止我的代码看起来像这样。
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");
}
}
} }
Just read in the full string, TrimStart() it and then use Substring() to get the parts you need 只需读入完整的字符串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);
In the last WriteLine() call you can use .ToString("00") to get the 2 digits you require 在最后一次WriteLine()调用中,您可以使用.ToString(“00”)来获取所需的2位数
Console.WriteLine(firstname + middleinitial + lastname + year.ToString("00") + "@mail.edu");
You should check that your users are entering a value between 2000 and 2099 though also. 您应检查您的用户是否也输入了2000到2099之间的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.