我想确保我的用户输入是6位数字并以数字1开头。我怎样才能确保输入以1开头?
private static void GetCustomerInfo(out string accNumberC)
{
string accNumberC;
Console.Write("Account number: ");
accNumberC = Console.ReadLine();
if (accNumberC == "" || accNumberC.Length < 6 || accNumberC.Length > 6)
{
Console.WriteLine("Invalid data entered - no value redorded");
accNumberC = null;
}
}
答案 0 :(得分:1)
您可以像使用索引一样访问第一个字符:
if (accNumberC == "" || accNumberC.Length != 6 || accNumberC[0] != '1') //or use StartsWith
{
Console.WriteLine("Invalid data entered - no value redorded");
accNumberC = null;
}
答案 1 :(得分:1)
if (string.IsNullOrEmpty(accNumberC) || accNumberC.Length != 6 || !accNumberC.StartsWith("1"))
{
Console.WriteLine("Invalid data entered - no value redorded");
}
答案 2 :(得分:0)
只需使用accNumberC[0]=='1'
比较并标记错误。
答案 3 :(得分:0)
您可以尝试将输入的字符串解析为整数值:
int val;
if (!int.TryParse(accNumberC, out val))
{
// string cannot be parsed as int.
Console.WriteLine("Cannot parse entered value");
}
else if (val < 100000 || val > 199999)
{
// value is not 6 digits length or doesn't start with 1.
Console.WriteLine("Invalid data entered - no value redorded");
}
else
{
// acceptable value here.
}
答案 4 :(得分:0)
另一种解决方案是使用正则表达式。这是一个例子:
bool isValid(string accountNumber)
{
if(String.IsNullOrWhiteSpace(accountNumber)) return false;
var result = System.Text.RegularExpressions.Regex.Match(accountNumber,"^1\\d{5}$");
return result.Success;
}