简体   繁体   English

在C#中验证字符串

[英]Validating String in C#

Hi so im trying to validate my string here so that it does not allow any input that starts with: "911" so if you type: "9 11", "91 1", "9 1 1" it should go through my if statement. 嗨所以我试图在这里验证我的字符串,以便它不允许任何以“911”开头的输入,所以如果你输入:“9 11”,“91 1”,“9 1 1”它应该通过我的if声明。 It works with "911" but not the others, here's my code: 它适用于“911”而不是其他,这是我的代码:

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;
                    }
                }
            }
        }
    }
}

As you can see I am trying to use " input.StartsWith("9 11") ;" 如你所见,我正在尝试使用“ input.StartsWith("9 11") ;” but it does not work... 但它不起作用......

You could use the Replace method of String ; 你可以使用StringReplace方法; the condition you describe can be formulated as follows. 您描述的条件可以表述如下。

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

Use regular expressions for checks like this. 使用正则表达式进行这样的检查。

For example: 例如:

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

This regex matches all strings that include whitespaces in front of and between "911". 此正则表达式匹配包含“911”前面和之间的空格的所有字符串。

Use the following to check if the string starts with "911" : 使用以下命令检查字符串是否以"911"开头:

First create a copy from the input string but without any white spaces: 首先从输入字符串创建一个副本,但没有任何空格:

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

Then you can check if the string starts with 911 like this: 然后你可以检查字符串是否以911开头,如下所示:

if (input_without_white_spaces.StartsWith("911"))
{
    ...
}
bool valid = s.StartsWith("911") || 
            !string.Join("",s.Split()).StartsWith("911");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM