【问题标题】:How to determine if a user has capitalized a string input or not in C#?如何确定用户是否在 C# 中大写了字符串输入?
【发布时间】:2018-12-15 17:45:59
【问题描述】:

这是我的第一个问题!

我正在为大学编写C# 编码任务,其中玩家输入不同的操作,他们的操作结果会显示在控制台中。直到现在,我只是在说

(if firstInput == "Action" || firstInput == "action")

我听说我可以使用string.ToLower() 来简化它,但我似乎不知道怎么做。

对此的任何帮助将不胜感激,如果很明显,我很抱歉,我是C# noob:p

谢谢!

【问题讨论】:

  • 你试过if (firstInput.ToLower() == "action") 吗?我的意思是,从您发布的内容来看,这似乎是一个超级简单且重复的问题,并且代码示例总是很好
  • 您可以使用docs.microsoft.com/en-us/dotnet/api/…StringComparison.InvariantCultureIgnoreCase
  • 别被the Turkey test咬了。

标签: c# string input tolower


【解决方案1】:

如果用户是否用大写字母写第一个字母真的很重要,您可能需要比较指定不忽略大小写的字符串。

所以,既然"Action" != "action",那就试试String.Equals

bool isEqual = String.Equals(x, y, StringComparison.Ordinal);

那么,我会根据用户的输入执行.ToLower(),然后将其与原始输入进行比较。

【讨论】:

    【解决方案2】:

    这个想法是将输入转换为全部小写,这样无论用户输入什么,您都可以始终与小写字符串常量进行比较

    if (firstInput.ToLower() == "action") {
        ...
    }
    

    例子:

    "ACTION".ToLower()  ===>  "action"
    "Action".ToLower()  ===>  "action"
    "action".ToLower()  ===>  "action"
    

    【讨论】:

      【解决方案3】:

      string.ToLower() 返回一个包含所有小写字符的新 string。所以你的代码应该是这样的:

      if (firstInput.ToLower() == "action"){
      {
      

      .ToLower()firstInput 转换为全小写字符串。当您将其与"action" 的全小写字符串文字进行比较时,如果firstInput 包含任何大小写形式的"action"(Action、action、aCtIoN 等),则比较将成功。

      值得注意的是Microsoft .Net documentation 告诉你如何使用string.ToLower()。作为学习如何使用 C# 编程的一部分,您应该习惯于查看 Microsoft .Net 文档以了解如何使用该框架提供的功能。 string.ToLower() 文章提供了完整的代码示例:

      using System;
      
      public class ToLowerTest {
          public static void Main() {
      
              string [] info = {"Name", "Title", "Age", "Location", "Gender"};
      
              Console.WriteLine("The initial values in the array are:");
              foreach (string s in info)
                  Console.WriteLine(s);
      
              Console.WriteLine("{0}The lowercase of these values is:", Environment.NewLine);        
      
              foreach (string s in info)
                  Console.WriteLine(s.ToLower());
      
          }
      }
      // The example displays the following output:
      //       The initial values in the array are:
      //       Name
      //       Title
      //       Age
      //       Location
      //       Gender
      //       
      //       The lowercase of these values is:
      //       name
      //       title
      //       age
      //       location
      //       gender
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        • 2013-05-13
        • 1970-01-01
        相关资源
        最近更新 更多