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.
Related
This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 3 years ago.
I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).
Console.WriteLine("What time of year is it?");
var input = Console.ReadLine();
//earlier it was just
//time = Year.Winter;
switch (time)
{
case Year.Autumn:
Console.WriteLine("You're gonna have to grab the leaves");
break;
case Year.Summer:
Console.WriteLine("Let's go to the beach");
break;
case Year.Winter:
Console.WriteLine("Better to warm up at home");
break;
case Year.Spring:
Console.WriteLine("Best time of the year!");
break;
default:
Console.WriteLine("I don't know this time of year");
break;
}
I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?
You can parse a try to parse a string into an Enum by using one of the Enum class.
In particular, you can use the typed method TryParse in this eay
var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
// use r
else
Console.WriteLine("Please enter the correct value.");
You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition
time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));
The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment
This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
C# Case insensitive string comparison [duplicate]
(3 answers)
Closed 10 months ago.
Need to have string comparison case insensitive for .net winforms application. It is not a problem when strings are compared in my code, but I need this everywhere.
For ex.: there is combobox with items populated from SQL data, where value member is uppercase string, but entity field bound to this combobox as value is allowed to have value (string) lowercase. Same for the rest elements.
You cannot change the default comparison for strings in .net. .net is a case sensitive language. It has specific methods for comparing strings using different levels of case sensitivity, but (thank goodness) no global setting.
You can use this:
string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
Or extension method:
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;
}
}
and you can call it like this:
bool result = "This is a try".Contains("TRY",
StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(result);
Use
if (string1.ToLower().Equals(string2.ToLower()))
{
#something
}
without the code, there is no other advice i can offer you :/
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");
}
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
}
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.....