嗨,所以即时尝试验证我的字符串,以便它不允许任何以“911”开头的输入,所以如果您键入:“9 11”,“91 1”,“9 1 1 “它应该通过我的if语句。它与“911”,而不是其他人,这是我的代码:在C中验证字符串#
using System;
using System.Collections.Generic;
namespace Phone_List
{
class Program
{
static void Main(string[] args)
{
var phoneList = new List<string>();
string input;
Console.WriteLine("Input: ");
while ((input = Console.ReadLine()) != "")
{
phoneList.Add(input);
for (int i = 0; i < phoneList.Count; i++)
{
if (phoneList[i].Substring(0, 3) == "911")
{
input.StartsWith("9 11");
input.StartsWith("9 1 1");
input.StartsWith("91 1");
Console.WriteLine("NO");
Console.ReadLine();
return;
}
else
{
Console.WriteLine("YES");
Console.ReadLine();
return;
}
}
}
}
}
}
正如你可以看到,我试图用“input.StartsWith("9 11")
”;但它不工作...
这些代码并没有真正太大的意义,你正在写的条件块内的'StartsWith'检查时,它已经与“911”,并没有别的开始。此外,您必须检查'StartsWith'是否返回'true',现在,您的支票什么也不做。 –
谷歌“正则表达式”。它们是为了用这样的规则验证字符串而设计的结构。 – t3dodson
使用正则表达式。这里以911开始的所有字符串的正则表达式应该是“911. *”。当出现匹配时,您知道当前输入始于911 –