当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to neglect Capital and small alphabet in all

问题描述:

string usertype;

usertype = Console.ReadLine();

if (usertype== "Yahoo")

{

Console.WriteLine("You typed Yahoo therefore we are now login to Yahoo Page");

Console.ReadLine();

}

Nothing wrong with t he code except: If user types Yahoo then it shows answer. I want user; if he types yahoo then answer should be the same.

网友答案:
string usertype;
usertype = Console.ReadLine();

if (string.Equals(usertype,"Yahoo",StringComparison.OrdinalIgnoreCase))
{ 
  Console.WriteLine("You typed Yahoo therefore we are now login to Yahoo Page");
  Console.ReadLine();
}
网友答案:

You can use String.ToLower() method with a similar code to this:

string usertype;
usertype = Console.ReadLine();

if (usertype.ToLower() == "yahoo")
{ 
  Console.WriteLine("You typed Yahoo therefore we are now login to Yahoo Page");
}
网友答案:

Instead of comparing using "==" operator, use String.Equals method.

If you need a case-insensitive comparison just use System.StringComparison.OrdinalIgnoreCase StringComparison enum.

Description from MSDN:

basic ordinal comparison (System.StringComparison.Ordinal) is case-sensitive, which means that the two strings must match character for character: "and" does not equal "And" or "AND". A frequently-used variation is System.StringComparison.OrdinalIgnoreCase, which will match "and", "And", and "AND". StringComparison.OrdinalIgnoreCase is often used to compare file names, path names, network paths, and any other string whose value does not change based on the locale of the user's computer. For more information

Further info can be found here

In your case I would use the following condition:

    if (usertype.Equals("yahoo", StringComparison.OrdinalIgnoreCase))
        //then do whatever you want...

Another option is to lowercase everything but the first option is preferred.

if (usertype.ToLower() == "yahoo")
    //then do whatever you want...
分享给朋友:
您可能感兴趣的文章:
随机阅读: