[英]How do I limit the number of characters that can be in a string?
我正在編寫一個程序來限制輸出中可以包含的字符數。 基本上是學生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");
}
}
}
只需讀入完整的字符串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之間的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.