C# If Equals Case insensitive [duplicate] - c#

This question already has answers here:
Comparing two strings, ignoring case in C# [duplicate]
(8 answers)
Closed 9 years ago.
The following code will open up a Message Box containing the word "Fail".
Is there a way to make the if statement case insensitive, so that the if statement passes and opens a mbox containg "Pass" without converting the character/string to upper/lower case?
here is the code:
public partial class Form1 : Form
{
string one = "A";
string two = "a";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (one == two)
{
MessageBox.Show("Pass");
}
else
{
MessageBox.Show("Fail");
}
}
}
Thanks in advance

You could use this
string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase)
Your code would be
if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))
{
MessageBox.Show("Pass");
}
else
{
MessageBox.Show("Fail");
}
Using CurrentCultureIgnoreCase :
Compare strings using culture-sensitive sort rules, the current
culture, and ignoring the case of the strings being compared.
More info here

if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))
From MSDN:
StringComparer.CurrentCultureIgnoreCase Property
Gets a StringComparer object that performs case-insensitive string comparisons using the word comparison rules of the current culture.

Various options:
if (String.Compare(one, two, StringComparison.CurrentCultureIgnoreCase) == 0) {
// they are equal
}
Option 2:
if ((one ?? "").ToLower() == (two ?? "").ToLower())
// they are equal
}
There are tons of other options, but these should get you started!
NOTE - One thing people regularly forget with string comparisons is null values. Be sure to watch for null values however you do your comparison. The second option I presented does an excellent job of this.

Use a case insensitive string comparer:
if(StringComparer.OrdinalIgnoreCase.Equals(one, two))
You should also consider if this comparison needs to be done in the user's culture.

You should use .Equals() to compare strings. Then you can use StringComparison.OrdinalIgnoreCase as the third argument to ignore case.

You can as well use this
string one = "obi";
string two = "Obi";
if(one.Equals(two, StringComparison.OrdinalIgnoreCase))
{
/* Your code */
}

if(one.ToLower() == two.ToLower())
{
//Do stuff
}

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-]+$

Case Insensitive Interpretation C# [duplicate]

This question already has answers here:
How can I do a case insensitive string comparison?
(9 answers)
LINQ Contains Case Insensitive
(11 answers)
Closed 5 years ago.
I'm making a text game, and I have one method for getting the input from the player and another for processing that input. However, it only works if the player types the command all in lowercase. I want it to ignore case.
public string GetInput()
{
var Test = true;
while (Test)
{
response = Console.ReadLine();
if (validWords.Contains(response))
{
Test = false;
ProcessInput(response);
}
else
{
Console.WriteLine("I'm sorry, I do not understand.");
}
}
return response;
}
public void ProcessInput(string response)
{
switch (response)
{ //Switch statements for responses here
}
}
I've tried using a few other responses I've found here, but they all still only work with lowercase input(using LINQ, string.IndexOf/Equals/etc.). Ideas?
Use string comparer which ignores string case as second parameter for Contains method:
validWords.Contains(response, StringComparer.OrdinalIgnoreCase)
You can make every input you receive, Lower-Case, using ToLower().
Example:
string response = Console.ReadLine().ToLower();
You can add .ToLower() after the readline, as followed:
response = Console.ReadLine().ToLower();
Everything read in from the console will be in lowercase.
You can read more about the ToLower method in the MSDN documentation.
Furthermore, also see the following question if you expect input of certain cultures: string.ToLower() and string.ToLowerInvariant().
Change the text you have to lower using .ToLower().
You're currently using if (validWords.Contains(response)) to check whether the user's response is contained within your validWords list. (I'm assuming).
What you can do is use the following LINQ expression:
if (validWords.Where(w => w.ToUpper().Equals(response.ToUpper())).Count() == 1)
This validates against both upper case strings.

String Comparison with overload [duplicate]

This question already has answers here:
Comparing two strings, ignoring case in C# [duplicate]
(8 answers)
Closed 8 years ago.
I have similar scenario in my project, I have to compare two strings, and Strings are same. But some characters are in capital letters.
string first = "StringCompaRison";
string second = "stringcoMparisoN";
if(first.Equals(second))
{
Console.WriteLine("Equal ");
}
else
Console.WriteLine("Not Equal");
For me, output should be equal, am very new to Programming, Which overload to use? Can someone tell me the efficient way to compare?
You're looking for this:
if (first.Equals(second, StringComparison.InvariantCultureIgnoreCase))
String.Equals documentation
StringComparison Enumeration documentation
There are lot of other ways to do this,
When you call a string comparison method such as String.Compare, String.Equals, or String.IndexOf, you should always call an overload that includes a parameter of type StringComparison so that you can specify the type of comparison that the method performs.
Overloads:
CurrentCulture, CurrentCultureIgnoreCase, InvariantCulture, InvariantCultureIgnoreCase, Ordinal and OrdinalIgnoreCase
For more information http://msdn.microsoft.com/en-us/library/system.stringcomparison(v=vs.110).aspx
Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance and as your safe default for culture-agnostic string matching,
You can use String.ToUpper, String.ToLower , but this will allocate memory for string.
This is the best way to do,
string first = "StringCompaRison";
string second = "stringcoMparisoN";
if(first.Equals(second,StringComparison.OrdinalIgnoreCase)
{
Console.WriteLine("Equal ");
}
else
Console.WriteLine("Not Equal");
Use String.Compare
bool match = (String.Compare(first, second, true) == 0);
if (match)
{
Console.WriteLine("Equal");
}
else
{
Console.WriteLine("Not equal");
}

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

Case Insensitive comparison in C# [duplicate]

This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
Closed 9 years ago.
I am comparing two strings using following code
string1.Contains(string2)
but i am not getting results for case insensitive search. Moreover I cant use String.Compare coz i dont want to match the whole name as the name is very big.
My need is to have case insensitive search and the search text can be of any length which the String1 contains.
Eg Term************** is the name.
I enter "erm" in textbox den i get the result. but when i enter "term" i dont get any result.
Can anyone help me :)
Try this:
string.Equals("this will return true", "ThIs WiLL ReTurN TRue", StringComparison.CurrentCultureIgnoreCase)
Or, for contains:
if (string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0)
I prefer an extension method like this.
public static class StringExtensions
{
public static bool Contains(this string source, string value, StringComparison compareMode)
{
if (string.IsNullOrEmpty(source))
return false;
return source.IndexOf(value, compareMode) >= 0;
}
}
Notice that in this way you could avoid the costly transformation in upper or lower case.
You could call the extension using this syntax
bool result = "This is a try".Contains("TRY", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(result);
Please note: the above extension (as true for every extension method) should be defined inside a non-nested, non-generic static class See MSDN Ref
Convert both strings to a same case, either upper or lower.
string1.ToUpper().Contains(string2.ToUpper());
Why not this:
if (string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0)
{
}
string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
You can either convert both strings to uppercase, or use regular expressions:
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string string1 = "TermSomething";
string string2 = "term";
bool test1 = string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
bool test2 = Regex.IsMatch(string1, Regex.Escape(string2), RegexOptions.IgnoreCase);
}
}
Note that if you use regular expressions you should escape the search string, so that special regex characters are interpreted literally.
Regex.IsMatch(string1,string2,RegexOptions.IgnoreCase);
This returns boolean value.....

Categories