Check What Letters are in a String - c#

I am making a Hangman Game in C# in WPF, and I am wondering if there is a way to check what letters are in a string so that if a letter is choosen the program can determine if the letter is in the chosen word or not.
Ex.
String StackOverFlow; //Sample String
//If Letter "A" is chosen,
private void AButt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//What Would I Put Here?
}

You could use Contains(), but that is going to be case sensitive. Hangman is not.
The easiest way to handle that is to use IndexOf() instead:
if(StackOverFlow.IndexOf("A", StringComparison.CurrentCultureIgnoreCase) > -1)
{
// Found
}
else
{
// Not Found
}

You could use the String.Contais method. And don't create one event handler for each letter - create only one which checks what letter was input, then do something according to it existing in the string or not.

Use Contains:
StackOverFlow.Contains("A");
If you also want to know where in the word the letter first appears, you can use IndexOf:
StackOverFlow = "EXAMPLE"
StackOverFlow.IndexOf("A"); //returns 2
StackOverFlow.IndexOf("B"); //returns -1 because it is not present

You can use ToLower() first to tackle case-sensitivity:
StackOverflow.ToLower().Contains("a")

Related

Regex for string without spacial characters or spaces [duplicate]

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

Contains and Regex Returns true but not with exact match

I am stumped on how to figure out the condition. Basically I have information from a list into a string to use Contains and Regex. I need to figure out if the user selected the "Other" option and if so then do something. However in the same list there are additional values to choose from that start with "Other" as well.
Example Data:
Fire Material
Other
Other Chemical
Example Code:
if(MaterialList.ToString().Contains("Other"))
{
"Do This If Other Is Selected";
}
else
{
"Do That If Other Isn't Selected";
}
It works fine if the user selects just "Other" however, if the user doesn't select "Other" but selects "Other Chemical" the condition still returns true.
I have also tried the following and it behaves the same:
public static bool ExactMatch(string input, string match)
{
return Regex.IsMatch(input, string.Format(#"{0}", Regex.Escape(match)));
//actually doesn't find the exact match - just a portion of the string
}
Probably Contains or Match shouldn't be used but not sure how to solve the problem.
Looks like you could use Linq instead:
if (MaterialList.Any(m => m == "Other"))
...
You can use String.EndsWith() function in your case
From MSDN:
Determines whether the end of this string instance matches the
specified string.
try this:
if(MaterialList.ToString().EndsWith("Other"))
{
"Do This If Other Is Selected";
}
else
{
"Do That If Other Isn't Selected";
}
Why not use
public static bool ExactMatch(string input, string match)
{
return input == match;
}
or you're sick by do-everything-with-regex?
Thanks all. Figured it out.
if(MaterialsList.ToString().Split('\t').Contains("Other"))

How to check if the tape starts with special characters

I need to track to string began with the required letters (Cyrillic or Latin or even any letters). But definitely not with numbers or special characters including space.
For start my task was only hanlde string starts with number but for now also certain characters.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int i;
if (isRoot && (int.TryParse(textBox1.Text.Trim(), out i)))
What should I do for characters?? Use something like this (but in this case I need to make conditions for all characters):
(textBox1.Text.Trim(). StartsWith("%") || textBox1.Text.Trim().StartsWith("-") || ......
)
Is there some better ways?? Coz if you propose to allow only letters then it is a bad idea because it can be given a different language.. So what?
You can use a Regular Expression to handle this functionality.
For example:
This snippet makes sure an input file path is correctly formatted.
// [drive_letter]:\ or \\[server]\ or [drive name]:\
private const string PathPattern = "^[A-z]:[\\\\/]|^\\\\|^.*[A-z]:[\\\\/]";
var matchMaker = new Regex(PathPattern);
var success = matchMaker.Matches(inputPath);
In your case you want to identify different characters and trim them, so you'd identify those strings with a Regex expression then carry out your parsing logic.
This link has a list of all the Regex commands:
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

String.Equals how does it work?

I have string text="camel", and then I want to check if text contains letter "m", so I loop through it and checking it using:
if (text[i].Equals("m"))
but this never returns me true... why?
Since you are comparing a character with a string this won't work.
Here's some more information on String comparisons
In this case you should use
if(text.Contains("m"))
As mentioned by #MattGreer, you're currently comparing a character and a string. This is because of the delimiter you've chosen for your literal, and because text[i] returns a character from a string rather than a substring of that string.
Please note the difference between using string literal delimiters (quote) and character literal delimiters (apostrophe):
if (text[i].Equals('m'))
Also, as others have stated, unless there is some reason you want to iterate through each character, String.Contains() would seemingly serve the intended purpose.
You need to find all occurences of a letter in a text as I understand it:
string text = "camel";
string lookup = "M";
int index = 0;
while ( (index = text.IndexOf(lookup, index, StringComparison.OrdinalIgnoreCase) != -1)
{
// You have found what you looked for at position "index".
}
I don't think that you get it any faster than this.
Good luck with your quest.
The answers has been given to you by Kyle C, so this is how you complete the whole process and I'm gonna use winforms as an example:
private void button1_Click(object sender, EventArgs e)
{
string text = "camel";
if (text.Contains("m") || text.Contains("M"))//also checks for capital M
{
MessageBox.Show("True");
}
}
Miraclessss
Use Contains
You're asking if "camel" is the equivalent of "m" -- which it is not.
"camel" contains "m".

Allow user to only input text?

how do I make a boolean statement to only allow text? I have this code for only allowing the user to input numbers but ca'nt figure out how to do text.
bool Dest = double.TryParse(this.xTripDestinationTextBox.Text, out Miles);
bool MilesGal = double.TryParse(this.xTripMpgTextBox.Text, out Mpg);
bool PriceGal = double.TryParse(this.xTripPricepgTextBox.Text, out Price);
Update: looking at your comment I would advise you to read this article:
User Input Validation in Windows Forms
Original answer: The simplest way, at least if you are using .NET 3.5, is to use LINQ:
bool isAllLetters = s.All(c => char.IsLetter(c));
In older .NET versions you can create a method to do this for you:
bool isAllLetters(string s)
{
foreach (char c in s)
{
if (!char.IsLetter(c))
{
return false;
}
}
return true;
}
You can also use a regular expression. If you want to allow any letter as defined in Unicode then you can use this regular expression:
bool isOnlyLetters = Regex.IsMatch(s, #"^\p{L}+$");
If you want to restrict to A-Z then you can use this:
bool isOnlyLetters = Regex.IsMatch(s, #"^[a-zA-Z]+$");
You can use following code in the KeyPress event:
if (!char.IsLetter(e.KeyChar)) {
e.Handled = true;
}
You can use regular expression, browse here: http://regexlib.com/
You can do one of a few things.
User Regular Expression to check that the string matches your concept of 'Text' only
Write some code that checks each character against a list of valid characters. Or even use char.IsLetter()
Use the MaskedTextBox and set a custom mask to limit input to text only characters
I found hooking up into the text changed event of a textbox and accepting/rejecting the changes an acceptable solution. To "only allow text" is a rather vague definition, but you may as well check if your newly added text (the next char) is a number or not and simply reject all numbers/disallowed characters. This will make users feel they can only enter characters and special characters (like dots, question marks etc.).
private void UTextBox_TextChanged(object sender, EventArgs e)
{
string lastCharacter = this.Text[this.Text.Length-1].ToString();
MatchCollection matches = Regex.Matches(lastCharacter, "[0-9]", RegexOptions.None);
if (matches.Count > 0) //character is a number, reject it.
{
this.Text = Text.Substring(0, Text.Length-1);
}
}

Categories