【问题标题】:How do I compare the value of string array? [duplicate]如何比较字符串数组的值? [复制]
【发布时间】:2017-07-06 14:22:17
【问题描述】:

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

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")
}

结果输出不是我所期望的,有什么想法可以解决吗?

【问题讨论】:

  • 当您的数组中有超过 5 个索引时,为什么要使用 i&lt;5?为什么不MasterList.Length
  • 您的代码无法编译,您还没有说出您的期望。但很简单:if(!MasterList.Contains(YourName)){...} 而不是 for 循环。

标签: c# asp.net


【解决方案1】:

为什么不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】:

    为什么不使用Contains 方法?

    首先将以下行添加到您的 using 指令中:

    using System.Linq;
    

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

    if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    {
        Console.WriteLine("Your name is not among the list")
    }
    

    【讨论】:

    • 我觉得这里用Contains不安全,即使是Contains,也可能不是名字,应该完全匹配
    【解决方案3】:
    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");
    

    【讨论】:

    • 投反对票的人可以给@Peter一些cmets,他是一个相对较新的用户:)
    • @garfbradaz 如果彼得无法弄清楚他的答案有什么问题,那么总是How to write a good answer
    • 将字符串与== 运算符进行比较可能会产生不可预知的结果(我没有投反对票)。您正在引用以查看它是否是完全相同的对象(无论内容如何,​​这些字符串通常都不是)。
    • 谢谢伙计...它就像我想要的那样工作!谢谢@Peter Meadley
    猜你喜欢
    • 2023-02-05
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多