简体   繁体   English

如何在 C# 中使字符串输入不区分大小写?

[英]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.因此,在我学习 C# 的过程中,我试图创建一个交互式故事,该故事根据用户提交的某些输入进行更改。 If the user types in "Bobby" in this case, the narrator begins to talk like Hank Hill.如果用户在这种情况下输入“Bobby”,叙述者就会开始像 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 语句的格式设置为:

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

But that did not trigger the if command with different letter cases但这并没有触发具有不同字母大小写的 if 命令

 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.我希望有一行代码在任何情况下都会触发 if 条件。 However, everything I tried has not changed that.然而,我尝试的一切都没有改变这一点。 It needs to be specifically "Bobby" or it will trigger the else condition它需要特别是“Bobby”,否则会触发 else 条件

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).从技术上讲,使用不区分大小写的比较而不是更改被比较字符串的大小写更好,因为ToUpper()并不总是按预期工作(从比较的角度来看)与所有语言(字母表)。 See "the Turkish 'i'" section in this article on case folding for more info.有关详细信息,请参阅本文中有关案例折叠的“土耳其语‘i’”部分。

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.要在不修改原始字符串的情况下解决您的问题,您可以使用String.Equals方法,该方法接受要比较的字符串的参数以及指定要使用的比较类型的参数。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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