如何比较字符串数组的值?

时间:2017-07-06 14:22:17

标签: c# asp.net

我已经声明了一个字符串数组,我希望与用户给出的名称进行比较,

string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

结果输出不是我所期望的,任何想法我怎么能去做?

3 个答案:

答案 0 :(得分:2)

为什么不使用Contains方法?

首先在使用指令中添加以下行:

$this->uri->segment('3'); //where 3 is for 3rd param

然后,删除for循环并改为使用以下行:

using System.Linq;

答案 1 :(得分:2)

为什么不Contains

  string[] MasterList = new string[] {
    "Askay", "Puram", "Raman", "Srinivasa",
    "Gopal", "Rajesh", "Anju", "Nagara",
  };

  Console.WriteLine("Enter your name: ");
  string YourName = Console.ReadLine();

  // StringComparer.OrdinalIgnoreCase if you want to ignore case
  // MasterList.Contains(YourName) if you want case sensitive 
  if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine("Your name is not among the list")

答案 2 :(得分:-1)

bool found = false;
foreach (string s in MasterList)
{
    if(s == YourName)
    found = true;
}
if(found)
    Console.WriteLine("Your name is among the list");
else
    Console.WriteLine("Your name is not among the list");