簡體   English   中英

如何在C#中沒有特殊字符或數字的情況下用字母(az)詢問用戶輸入

[英]How to ask for user input with letters (a-z) only without special characters or numbers in C#

我正在嘗試創建一個程序,要求我對用戶輸入進行驗證,以僅接受給定數組5中的字母。因此,基本上,如果我是用戶,則不允許輸入數字或特殊字符,如果我這樣做,我會得到一個錯誤。 有人可以幫我解決這個問題嗎? 我已經嘗試過各種搜索,但無法找到解決方案。 我感謝我能得到的任何幫助。 這就是我到目前為止所擁有的。

class Program
{
    static void Main(string[] args)
    {
        char[] arr = new char[5];

        //User input
        Console.WriteLine("Please Enter 5 Letters only: ");

        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = Convert.ToChar(Console.ReadLine());
        }
        //display
        for(int i = 0; i<arr.Length; i++)
        {
            Console.WriteLine("You have entered the following inputs: ");
            Console.WriteLine(arrArray[i]);
        }
    }
}
 char[] arr = new char[5];

            //User input
            Console.WriteLine("Please Enter 5 Letters only: ");
            string s = "abcdefghijklmnopqrstuvwxyz";
            for (int i = 0; i < arr.Length;)
            {
                string sChar = Console.ReadLine().ToLower();
                if (s.Contains(sChar) && sChar.Length == 1)
                {
                    arr[i] = Convert.ToChar(sChar);
                    i++;
                }
                else
                {
                    Console.WriteLine("Please enter a character from A-Z");
                    continue;
                }
            }
            //display
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine("You have entered the following inputs: ");
                Console.WriteLine(arr[i]);
            }

在此輸入圖像描述

我建議使用正則表達式(正則表達式)。

對於數字和字母,正確的正則表達式為:

string numbersLettersRegex = @"^[a-zA-Z0-9\_]+$"

然后,您只需對照該正則表達式進行檢查:

if (Regex.isMatch(numbersLettersRegex, arr[i] 
{ 
    //do stuff
}

else 
{
    //print error Message
}

將您要驗證的字符串傳遞給此功能:

public bool checkYo(String myString)
{
    return Regex.IsMatch(myString, @"^[a-zA-Z]+$");
}

這將檢查az和AZ ..如果你只想要az,只需從上面的函數中刪除AZ部分。 希望這可以幫助。

嘗試這個

static void Main(string [] args){

char[] arr = new char[5];
Console.WriteLine("Please Enter 5 Letters only: ");
string inputstring = Console.ReadLine();

if (Regex.IsMatch(inputstring, @"^[a-zA-Z]+$"))
{
    arr = inputstring.ToCharArray();
    Console.WriteLine("You have entered the following inputs: ");

    //display
    for (int i = 0; i < arr.Length; i++)
    {
        Console.Write(arr[i]);
    }
    Console.ReadLine();
}
else
{
    Console.WriteLine("Enter valid inputs and try again");
    Console.ReadLine();
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM