Reputation: 125
I have a question. I'm researched it on the web and of course with the search function here on stackoverflow. I also found a few similiar question but they where either in another programming language or not exactly I want to do. So here is my question in detail:
I'm creating a simple console Hangman game (im a beginner). I'm doing this just on my own because I think I learn the most if I do it on my own. Anyway I ask the user for his word and save it into a variable. I also make it Uppercase. Now I want to check if this word only contains valid letters from the alphabet. Than I want to put this in a if condition so he will be ask again if he enters for example a number.
But I have no idea how to do this? I tried it with the tryparse method and contains but I can't come to a solution. So I'm asking you kindly how to do this?
My code:
class Hangman
{
private string enteredWord;
private char guessedLetter;
public void Start()
{
enteredWord = AskUserForWord();
Console.WriteLine(enteredWord);
Console.ReadLine();
}
private string AskUserForWord()
{
Console.WriteLine("Bitte gib ein Wort ein das es zu erraten gilt. Sag deinem Mitspieler er soll weg sehen: ");
string word = ToUpper(Console.ReadLine());
if ()
return word;
}
private string ToUpper(string word)
{
return word.ToUpper();
}
}
Upvotes: 0
Views: 777
Reputation: 21
You can use regular expressions.
For alphabets,
Regex.IsMatch(word, @"^[a-zA-Z]+$");
Upvotes: 1
Reputation: 1
You may also try with a Regular expression.
Match match = Regex.Match("Testing a valid input ", @"(?i)^[a-z]+");
if (match.Success)
{
//validation passed
}
Upvotes: 0
Reputation: 142
read up on Regex aka Regular expressions, they are good for describing exactly how you want your input to be, in your case it would be something like:
Regex(@"^[a-zA-Z]*");
this means only accept strings which consist of alphabetic characters.
look at this example https://msdn.microsoft.com/en-us/library/3y21t6y4(v=vs.110).aspx to understand how to use it.
Upvotes: 0
Reputation: 48
This should do the job :
bool result = input.All(Char.IsLetter);
and also a regex solution :
Regex.IsMatch(theString, @"^[\p{L}]+$");
The Char.IsLetter is the better solution since it counts as a letter any language alphabets. This regex will also count them but still it looks more compact with IsLetter
Upvotes: 1
Reputation: 1949
It can be checked with this.
bool isLettersOnly = !word.Any(c => !char.IsLetter(c));
Upvotes: 0
Reputation: 2940
First reference system.linq:
using System.Linq;
then modify your AskUserForWord()
function:
while (true)
{
Console.WriteLine("Bitte gib ein Wort ein das es zu erraten gilt. Sag deinem Mitspieler er soll weg sehen: ");
string word = Console.ReadLine().ToUpper();
if (word.All(c => char.IsLetter(c))
return word;
Console.WriteLine("Also bitte, nur Buchstaben sind hier erlaubt!");
}
Upvotes: 1