2015-09-26 121 views
3

嗨,所以即时尝试验证我的字符串,以便它不允许任何以“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")”;但它不工作...

+0

这些代码并没有真正太大的意义,你正在写的条件块内的'StartsWith'检查时,它已经与“911”,并没有别的开始。此外,您必须检查'StartsWith'是否返回'true',现在,您的支票什么也不做。 –

+1

谷歌“正则表达式”。它们是为了用这样的规则验证字符串而设计的结构。 – t3dodson

+0

使用正则表达式。这里以911开始的所有字符串的正则表达式应该是“911. *”。当出现匹配时,您知道当前输入始于911 –

回答

1

使用正则表达式进行此类检查。

例如:

Regex.IsMatch(input, "^\\s*9\\s*1\\s*1"); 

此正则表达式匹配的所有字符串,包括以和“911”之间的空格前面。

+0

我通过编写这段代码得到一个:“无法识别转义序列”。 – Cleon

+0

@Cleon对不起,忘了逃避反斜杠。通常,转义序列的写法与'\ s'类似,但'\'是字符串中的特殊字符,因此您必须将其转义。这导致'\\ s'。更新后的答案现在是正确的 – Domysee

0

使用以下方法来检查字符串"911"开始:

首先创建一个从输入字符串的副本,但没有任何空格:

string input_without_white_spaces = 
    new string(input.ToCharArray().Where(x => !char.IsWhiteSpace(x)).ToArray()); 

然后您可以检查字符串是否以911开头,如下所示:

if (input_without_white_spaces.StartsWith("911")) 
{ 
    ... 
} 
2

您可以使用Replace方法String;您描述的情况可以如下表述。

input.Replace(" ", "").StartsWith("911") 
+0

所以我试图在我的if语句之前编写这段代码,它仍然不起作用,我是否错过了某些东西? – Cleon

0
bool valid = s.StartsWith("911") || 
      !string.Join("",s.Split()).StartsWith("911");