如何使我的程序只接受C#中的大写字母?

如何使我的程序只接受C#中的大写字母?,c#,visual-studio,C#,Visual Studio,这是一个C#问题。我想让我的程序只接受大写字母。我已经设法让它拒绝小写字母,但我不知道如何让它拒绝数字和其他字符。谢谢你的帮助 #region Question3 /* Write an application named EnterUppercaseLetters that asks the user * to type an uppercase letter from the keyboard. If the character entered * is an

这是一个C#问题。我想让我的程序只接受大写字母。我已经设法让它拒绝小写字母,但我不知道如何让它拒绝数字和其他字符。谢谢你的帮助

#region Question3
    /* Write an application named EnterUppercaseLetters that asks the user
     * to type an uppercase letter from the keyboard. If the character entered 
     * is an uppercase letter, display OK; if it isn't an uppercase letter, 
     * display an error message. The program continues until the user types an exclamation point.
     */
static void  EnterUppercaseLetters()
    {
        //char letter;
        bool toContinue = true;
        do
        {
            Console.Write("Enter an uppercase letter: ");
            //string input = Console.ReadLine();
            char letter = Convert.ToChar(Console.ReadLine());
            //double number = Convert.ToDouble(input);
            //int number = Convert.ToInt32(letter);
            if (letter == '!')
            {
                toContinue = false;
            }
            else
            {
                if (letter == Char.ToUpper(letter))
                {
                    Console.WriteLine($"{letter} OK");
                }
                else
                {
                    Console.WriteLine("ERROR!");
                    continue;
                }
            }
        } while (toContinue);
        Console.WriteLine();
    }

#endregion

我想你可以用regex来做这个

Regex.IsMatch(input, @"^[A-Z]+$");
这将检查您的字符串是否包含任何非大写字母的字符。

一种可能性是:

char.GetUnicodeCategory(letter) != UnicodeCategory.UppercaseLetter

请注意,如果用户键入空字符串或长度超过1的字符串,则
Convert.ToChar
将引发未处理的异常。您可以考虑检查字符串长度,或者使用<代码>控制台。RealKEY < /C> >而不是<代码>控制台。RealdLe> <代码> < /P> < P> @ Moe -您所拥有的是好的…但也许你不想进入整个队伍。您可以尝试以下方法:

static void Main(string[] args)
{
    char ch;
        
    //input character 
    Console.WriteLine("Enter an UPPER CASE character, or '!' to exit: ");
    while ((ch = Console.ReadKey().KeyChar() != '!')
    {
       if (IsUpper(ch))
            Console.WriteLine("Input character is {0}: OK", ch);
       else 
            Console.WriteLine("Input character is {0}: ERROR!", ch);
    }
}
这将在您输入任何击键时立即响应。当您键入“!”时,它将立即退出。它将打印“OK”(大写字符)或“ERROR!”否则

相关文件(针对我们的巡回朋友杰普·斯蒂格·尼尔森):


使用
Char.isleter
?或者最简单的选择可能是使用一个callMixes三种类型,即
bool
,为您处理两种检查,
char
System.ConsoleKeyInfo
IsUpper
static
。我更喜欢我的解决方案:)另外:有时回答问题就像打鼹鼠:问题往往在我完成回答之前就被关闭或删除了。所以我养成了一个习惯,尽快回答一个粗略的回答,然后马上回去复习。当我还没来得及回答好的问题就结束了,这是令人沮丧的,当我还在修改的时候,人们“批评”的时候,这更令人沮丧。