Reputation: 173
Here I have some simple C# code;
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (name == "ashley")
{
Console.WriteLine("You entered: " + name);
}
Console.Read();`
If the user enters ashley it will display "You entered ashley". However if the user enters Ashley or AsHlEy it won't work. What do I need to add to this or how to format so it will ignore the case?
Upvotes: 0
Views: 13487
Reputation: 532505
Use string.Equals
with an appropriate StringComparison
if (string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase))
{
...
}
If you know that the variable is not null you can also use
if (name.Equals("ashley", StringComparison.CurrentCultureIgnoreCase))
{
...
}
To answer your question in the comments, a do-while
loop can be used to loop until the question is answered correctly. The below will loop until the user enters something other than ashley
.
string name;
do
{
Console.WriteLine("Enter Name");
name = Console.ReadLine();
}
while (string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase));
You could combine this with a guard variable if you want different messaging:
string name;
bool nameIsCorrect = false;
do
{
Console.WriteLine("Enter Name");
name = Console.ReadLine();
nameIsAshley = string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase);
if (nameIsAshley)
{
Console.WriteLine("Stop entering 'ashley'");
}
}
while (!nameIsAshley);
Upvotes: 4
Reputation: 904
You can use the String.ToLower method
your test would be: if (name.ToLower() == "ashley")
Upvotes: 0
Reputation: 102428
Use ToLower like this:
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (name.ToLower() == "ashley")
{
Console.WriteLine("You entered: " + name);
}
Console.Read();`
Upvotes: 0
Reputation: 35409
String.Compare
takes a boolean parameter which allows you to ignore casing during comparison:
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (String.Compare(name, "ashley", true) == 0)
{
Console.WriteLine("You entered: " + name);
}
Console.Read();
Upvotes: 3
Reputation: 44038
change this:
if (name == "ashley")
to this:
if (name.ToLower() == "ashley")
Upvotes: 0