简体   繁体   中英

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.

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]* - Zero or more characters, from a to z

$ - 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:

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

Play with 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. 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. 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". Looking at the MSDN page for System.Char , we can see a couple methods that might help us out:

  • Char.IsWhiteSpace - tests whether a character is 'whitespace' (space, tab, newline)
  • Char.IsLetter - tests whether a character is a letter.
  • Char.IsUpper - tests whether a character is an uppercase letter.

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 . 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. 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. 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!

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:");
            }

        }

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