简体   繁体   English

我如何使C#忽略字母大小写

[英]How do I make c# ignore letter case

Here I have some simple C# code; 这里有一些简单的C#代码;

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". 如果用户输入ashley,它将显示“您输入了ashley”。 However if the user enters Ashley or AsHlEy it won't work. 但是,如果用户输入Ashley或AsHlEy,则将无法使用。 What do I need to add to this or how to format so it will ignore the case? 我需要为此添加什么内容或如何格式化,以便忽略大小写?

String.Compare takes a boolean parameter which allows you to ignore casing during comparison: String.Compare采用布尔值参数,该参数可让您在比较期间忽略大小写:

Console.WriteLine("Enter Name");
var name = Console.ReadLine();

if (String.Compare(name, "ashley", true) == 0)
{
    Console.WriteLine("You entered: " + name);
}

Console.Read();

Use string.Equals with an appropriate StringComparison 使用string.Equals适当的StringComparison

if (string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase))
{
   ...
}

If you know that the variable is not null you can also use 如果您知道该变量不为null,则也可以使用

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. 要在评论中回答您的问题,可以使用do-while循环进行循环,直到正确回答问题为止。 The below will loop until the user enters something other than ashley . 在用户输入除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);

change this: 改变这个:

if (name == "ashley")

to this: 对此:

if (name.ToLower() == "ashley")

Use ToLower like this: 像这样使用ToLower

Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (name.ToLower() == "ashley")
{
    Console.WriteLine("You entered: " + name);
}
Console.Read();`

You can use the String.ToLower method 您可以使用String.ToLower方法

your test would be: if (name.ToLower() == "ashley") 您的测试将是: if (name.ToLower() == "ashley")

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

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