简体   繁体   English

验证用户仅输入一个单词的答案,并且首字母大写

[英]Validating user only enters a one word answer and that the first letter is capitalized

I'm currently self-teaching myself C# and have had a pretty decent grasp on it, but I'm lost on how to validate that the user only enters one word answer and that it's capitalized otherwise I want to give them another chance to try. 我目前正在自学C#,并且对它掌握得相当不错,但是我迷失在如何验证用户仅输入一个单词答案以及是否大写的方式上,否则我想给他们另一个机会尝试。

This what I have so far: 这是我到目前为止所拥有的:

static void Main(string[] args)
    {
        //assigned variable
        string userInput;
        //intializing empty string
        string answerInput = string.Empty;
        //Creating loop
        while ((answerInput == string.Empty) || (answerInput == "-1"))
        {
            //This is asking the question to the user
            Console.WriteLine("Enter your favorite animal: ");
            //this is storing users input
            userInput = Console.ReadLine();
            //using function to validate response
            answerInput = letterFunc(userInput);
        }


    }
    //Creating function to only allow letters and making sure it's not left blank.
    private static string letterFunc (string validate)
    {
        //intializing empty string
        string returnString = string.Empty;
        //validating it is not left empty
        if(validate.Length > 0)
        {
           //iterating through the passed string
           foreach(char c in validate)
            {
                //using the asciitable to validate they only use A-Z, a-z, and space
                if ((((Convert.ToInt32(c)) > 64) && ((Convert.ToInt32(c)) < 91)) || (((Convert.ToInt32(c)) > 96) && ((Convert.ToInt32(c)) < 123)) || (Convert.ToInt32(c) == 32))
                {
                    //appensing sanitized character to return string
                    returnString += c;
                }
                else
                {
                    //If they try to enter a number this will warn them
                    Console.WriteLine("Invalid input. Use letters only.");
                }
            }
        }
        else
        {
            //If user enters a blank input, this will warn them
            Console.WriteLine("You cannot enter a blank response.");
        }
        //returning string
        return returnString;
    }

I was wondering if it's possible to do it inside the function I created to validate they only use letters and that it isn't empty with a detailed explaination. 我想知道是否有可能在我创建的用于验证他们仅使用字母的函数中进行操作,并且通过详细说明它不会为空。 Thanks. 谢谢。

Regular expressions are not that hard. 正则表达式并不难。 Problem is that sometimes you want to achieve something more complex, but that's not your case: 问题是有时候您想实现更复杂的目标,但事实并非如此:

private static string letterFunc (string validate)
{
    return new Regex("^[A-Z][a-z]*$").IsMatch(validate) ? 
           validate :
           string.Empty;
}

Explaining the expression: 解释表达式:

^ - Anchor: only matches when the text begins with the expression ^ -锚点:仅在文本表达式开头时匹配

[AZ] - Exactly one character, from A to Z [AZ] -正确的一个字符,从AZ

[az]* - Zero or more characters, from a to z [az]* -零个或多个字符,从az

$ - Anchor: only matches when the text ends with the expression $ -锚点:仅当文本以表达式结尾时才匹配

By using the two anchors, we want the full text to match the expression, not parts of it. 通过使用两个锚点,我们希望全文匹配表达式,而不是表达式的一部分。

If you want to allow capitals after the first letter (like CaT or DoG ), you can change it to: 如果要在第一个字母(例如, CaTDoG )之后使用大写字母,可以将其更改为:

^[AZ][a-zA-Z]*$

Play with Regex: https://regex101.com/r/zwLO6I/2 使用Regex玩: https : //regex101.com/r/zwLO6I/2

Regular expressions would be the standard way to do this, but looking at your code I don't think you're ready for them yet. 正则表达式将是执行此操作的标准方法,但是查看您的代码,我认为您还没有准备好使用它们。 This is not an insult by the way -- everyone was a beginner at some point! 顺便说一句,这不是侮辱-每个人在某个时候都是初学者!

Whenever you approach a problem like this, first make sure all your requirements are well-defined and specific: 每当您遇到这样的问题时,首先要确保所有要求都定义明确且具体:

  • One-word answer: In your code, you've defined it as "an answer that contains only letters and spaces". 单字答案:在代码中,您已将其定义为“仅包含字母和空格的答案”。 This might not be ideal, as it prevents people from entering answers like the dik-dik as their favorite animal. 这可能并不理想,因为它阻止人们输入像dik-dik这样的答案作为他们最喜欢的动物。 But let's stick with it for now. 但是,让我们暂时坚持下去。

  • Capitalized answer: Let's define this as "an answer where the first character is a capital letter". 大写答案:我们将其定义为“第一个字符为大写字母的答案”。

So taking the two requirements together, we're trying to validate that the answer starts with a capital letter and contains only letters and spaces. 因此,将这两个要求放在一起,我们正在尝试验证答案是否以大写字母开头并且仅包含字母和空格。

While coding, look at the language and framework you're using to see if there are convenience methods that can help you. 在编码时,请查看您使用的语言和框架,以查看是否有方便的方法可以为您提供帮助。 .NET has tons of these. .NET有很多此类功能。 We know we'll have to check the individual characters of a String , and a string is made up of Char s, so let's google "c# char type". 我们知道我们将必须检查String的各个字符,并且字符串是由Char的,因此让我们搜索“ c#char type”。 Looking at the MSDN page for System.Char , we can see a couple methods that might help us out: 查看MSDN页面上的System.Char ,我们可以看到一些可以帮助我们的方法:

  • Char.IsWhiteSpace - tests whether a character is 'whitespace' (space, tab, newline) Char.IsWhiteSpace测试字符是否为“空白”(空格,制表符,换行符)
  • Char.IsLetter - tests whether a character is a letter. Char.IsLetter测试字符是否为字母。
  • Char.IsUpper - tests whether a character is an uppercase letter. Char.IsUpper测试字符是否为大写字母。

So let's look at our requirements again and implement them one at a time: "starts with a capital letter and contains only letters and spaces". 因此,让我们再次看一下我们的需求并一次实现一个需求:“以大写字母开始,仅包含字母和空格”。

Let's call our user-input string answer . 让我们将其称为用户输入字符串answer We can check that the first letter is a capital like this (note we also make sure it HAS a first letter): 我们可以检查第一个字母是否为大写字母(请注意,我们还要确保它具有第一个字母):

bool isCapitalized = answer.Length > 0 && Char.IsUpper( answer[0] );

We can check that it contains only letters and spaces like this: 我们可以检查它是否仅包含字母和空格,如下所示:

bool containsOnlyLettersAndSpaces = true;
foreach( char c in answer )
{
    if( !Char.IsLetter( c ) && !Char.IsWhiteSpace( c ) )
    {
        containsOnlyLettersAndSpaces = false;
        break;
    }
}

containsOnlyLettersAndSpaces starts as true. containsOnlyLettersAndSpaces从true开始。 We then look at each character at the string. 然后,我们查看字符串中的每个字符。 If we find a character that is not a letter AND is not whitespace, we set containsOnlyLettersAndSpaces to false. 如果找到的字符不是字母也不是空格,则将containsOnlyLettersAndSpaces设置为false。 Also if we find an invalid character, stop checking. 另外,如果发现无效字符,请停止检查。 We know the answer is invalid now, no reason to check the rest of it! 我们知道答案现在无效,没有理由检查其余内容!

Now we can return our answer as a combination of the two validations: 现在,我们可以结合两个验证来返回答案:

return isCapitalized && containsOnlyLettersAndSpaces;

Here's the whole method: 这是整个方法:

    private bool IsValidAnimal( string answer )
    {
        bool isCapitalized = answer.Length > 0 && Char.IsUpper( answer[0] );

        bool containsOnlyLettersAndSpaces = true;
        foreach( char c in answer )
        {
            if( !Char.IsLetter( c ) && !Char.IsWhiteSpace( c ) )
            {
                containsOnlyLettersAndSpaces = false;
                break;
            }
        }

        return isCapitalized && containsOnlyLettersAndSpaces;
    }

Good luck with learning C#, and I hope this has helped you think about how to code! 祝您学习C#一切顺利,我希望这可以帮助您考虑如何编码!

I figured it out. 我想到了。 Thanks everyone for trying to help. 感谢大家的帮助。

        string answer;
        while (true)
        {
            Console.WriteLine("Enter your favorite animal:");
            answer = Console.ReadLine();

            if (new Regex("^[A-Z][a-z]*$").IsMatch(answer))
            {
                Console.WriteLine("You like {0}s. Cool!", answer);
                Console.ReadKey();
                break;
            }
            else
            {
                Console.WriteLine("'{0}' is not a valid answer.", answer);
                Console.WriteLine();
                Console.WriteLine("Make sure:");
                Console.WriteLine("You are entering a one word answer.");
                Console.WriteLine("You are only using letters.");
                Console.WriteLine("You are capitalizing the first letter of the word.");
                Console.WriteLine();
                Console.WriteLine("Try again:");
            }

        }

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

相关问题 除了任何单词的第一个字母外,如何在字符串中大写特定的两个字母的单词? - How do I capitalized specific two letter word in a string in addition to the first letter of any word? 除了任何单词的第一个字母,我如何将字符串中的两个字母的单词都大写? - How do I capitalized any two letter word in a string in addition to the first letter of any word? 每个超过 3 个字母的单词都以大写开头 + 第一行是大写 - 快速问题 - Every word longer than 3 letter starts with capitalized + first line is Upper case - quick question 正则表达式匹配单词中的第一个字母 - Regex to match the first letter in a word ONLY 验证用户输入是字母表中的一个字母 - Validating that user input is a letter of the alphabet 正则表达式仅“附加”或“替换”每个单词的第一个字母? - Regex “Append” or “Replace” only the first letter of each word? 如何解决:字符串中每个单词的大写首字母-一个字母单词除外 - How to Fix: Uppercase first letter of every word in the string - except for one letter words 仅在用户输入新数据时验证 - Validate only when user enters new data csharp方法单词的第一个和最后一个字母 - csharp method word first and last letter C#仅在第一个字母上排序字符串 - C# Sorting Strings only on first letter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM