如何让用户输入字母(A-Z),而不只是在C#中的特殊字符或数字 [英] How to ask for user input with letters (a-z) only without special characters or numbers in C#

查看:243
本文介绍了如何让用户输入字母(A-Z),而不只是在C#中的特殊字符或数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个需要我把一个验证用户输入只接受字母5.定数组中的程序所以基本上,如果我不允许我输入数字或特殊字符的用户,如果我这样做,我会得到一个错误。有人可以帮我这个?我身边有尝试过各种搜索,我一直没能找到一个解决方案。我感谢所有帮助我可以得到。
这是我到目前为止所。

 类节目
{
静态无效的主要(字串[] args)
{
的char [] =改编新的char [5];

//用户输入
Console.WriteLine(请输入只有5个字母:);

的for(int i = 0; I< arr.Length;我++)
{
改编[I] = Convert.ToChar(到Console.ReadLine());
}
//显示
的for(int i = 0; I< arr.Length;我++)
{
Console.WriteLine(你输入以下输入:);
Console.WriteLine(arrArray [I]);
}
}
}


解决方案

 的char [] =改编新的char [5]; 

//用户输入
Console.WriteLine(请输入只有5个字母:);
字符串s =ABCDEFGHIJKLMNOPQRSTUVWXYZ;
的for(int i = 0; I< arr.Length;)
{
串SCHAR =到Console.ReadLine()ToLower将()。
如果(s.Contains(SCHAR)及&放大器; sChar.Length == 1)
{
改编由[i] = Convert.ToChar(SCHAR);
I ++;
}
,否则
{
Console.WriteLine(请输入从A-Z字符);
继续;
}
}
//显示
的for(int i = 0; I< arr.Length;我++)
{
Console.WriteLine( 你输入以下输入:);
Console.WriteLine(ARR [I]);
}


I am trying to create a program that requires me to put a validation on the user inputs to only accept letters in a given array of 5. So basically if i am the user i am not allowed to input numbers or special characters, and if i do, i would get an error. Can someone help me out with this? I have tried various searches around and i have not been able to find a solution. I appreciate any help that i can get. This is what i have so far.

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

这篇关于如何让用户输入字母(A-Z),而不只是在C#中的特殊字符或数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆