简体   繁体   中英

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. It works with "911" but not the others, here's my code:

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") ;" but it does not work...

You could use the Replace method of String ; 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".

Use the following to check if the string starts with "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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