简体   繁体   中英

How to make string inputs case insensitive in C#?

So, in my quest to learn C#, I am attempting to create an interactive story that changes based on some of the input that the user had submitted. If the user types in "Bobby" in this case, the narrator begins to talk like Hank Hill. However, with how it's programmed, the input is case sensitive.

I have tried one thing suggestion that I saw which was to format the if statement as:

if (boyName.ToUpper() == "Bobby")

But that did not trigger the if command with different letter cases

 Console.WriteLine($"{beginning} \n What was the boy's name?");
 boyName = Console.ReadLine();
  if (boyName == "Bobby")
   {
   Console.WriteLine("That boy ain\'t right, I tell ya what... ");
   Console.ReadKey();
   Console.WriteLine($"{boyName} boy dang climbed a big ol' tree..."); 
   Console.ReadKey();
   }

   else
    {
    Console.WriteLine($"The kid named {boyName} climbed a tree...");
    Console.ReadKey();
    }

I expect to have a line of code that will trigger the if condition no matter the case. However, everything I tried has not changed that. It needs to be specifically "Bobby" or it will trigger the else condition

It's technically better to use a case-insensitive comparison rather than changing the case of the strings being compared, because ToUpper() will not always work as expected (from a comparison point of view) with all languages (alphabets). See "the Turkish 'i'" section in this article on case folding for more info.

To solve your issue without modifying the original strings, you can use the String.Equals method, which takes arguments for the strings to compare as well as one that specifies the type of comparison to use.

Therefore your code might look like this:

if (string.Equals(boyName, "Bobby", StringComparison.OrdinalIgnoreCase))

Or you could use the instance method version, which is a little shorter:

if (boyName.Equals("Bobby", StringComparison.OrdinalIgnoreCase))

你应该试试

if (boyName.ToUpper() == "Bobby".ToUpper())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM