【问题标题】:How to check if a string is contained in an array of strings? [duplicate]如何检查字符串是否包含在字符串数组中? [复制]
【发布时间】:2020-10-31 03:30:27
【问题描述】:

我大约需要一周的时间来学习 C#,之前的编码知识为 0。谁能告诉我为什么这不起作用?

string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH", 
                        "Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };

/*string afirmatives = "Yes";*/

Console.Write("Are you a Human? ");
string humanAnswer = Console.ReadLine();
string answer = (humanAnswer = afirmatives) ? 
   "That sounds like something a robot would say." 
   : "Invalid Input";
        
Console.WriteLine(answer);
Console.ReadLine();

我知道我可以让它只使用一个字符串值,但是我需要做些什么不同的事情来使用多个?

我是否必须制作多个 if else 行?

谢谢!

编辑

Xareth 帮我找到了答案。我需要添加“包含”某些东西或其他东西。这是新的可操作代码。

string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH", 
            "Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };
        Console.Write("Are you a Human? ");
        string humanAnswer = Console.ReadLine();
        string answer = humanAnswer = afirmatives.Contains(humanAnswer)
            ? "That's something a robot would say."
            : "Invalid Input";
        
        Console.WriteLine(answer);
        Console.ReadLine();

【问题讨论】:

  • 这能回答你的问题吗? Check if a value is in an array (C#)
  • 欢迎来到 SO!虽然像 “我用 0 个先前的编码知识学习 C# 大约一周。” 可能适合也可能不适合在帖子中,但通常最好不要将其包含在帖子中 标题。标题应该是对问题的简短描述,其编写方式与使用搜索引擎时几乎相同(尽管在SO上它应该是一个独立子句)。这将帮助其他人在今天和将来帮助您。祝你好运
  • 单个等号是赋值运算符而不是相等运算符。

标签: c#


【解决方案1】:

试试:

using System.Linq;  
string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH",
                        "Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };

/*string afirmatives = "Yes";*/

Console.Write("Are you a Human? ");
string humanAnswer = Console.ReadLine();
string answer = (afirmatives.Contains(humanAnswer)) ?
"That sounds like something a robot would say."
: "Invalid Input";

Console.WriteLine(answer);
Console.ReadLine();

请注意顶部的using System.Linq;

humanAnswer = afirmatives 不起作用的原因是因为=assignment operator。通过使用它,您试图使 humanAnswer 获取来自 afirmatives 的值。

要比较字符串,您应该使用equality operator。因此,在string afirmatives = "Yes"; 的情况下,以下内容将是有效的humanAnswer == afirmatives

但是,您将 humanAnswer 与数组进行比较,因此使用 Linq 是一种测试数组或列表是否包含值的简单方法

【讨论】:

  • 与其使用所有的大小写差异,为什么不简单地 String.ToUpper() 输入并将所有这些字符串都设为大写呢?例如,您的示例会在“yeP”或“YeP”上失败。否则,我喜欢你的示例代码。
  • bool found = Array.Exists(affirmatives, a => a.Equals(humanAnswer, StringComparison.InvariantCultureIgnoreCase)); string answer = found ? "" : "";
  • “humanAnswer = afirmatives 不起作用的原因是因为” - 可以说我认为我们可以忽略这一点,因为 OP 发布了带有 [编译错误]()。 C# 不是 c/c++。 +1 无论如何
  • 哇。谢谢!我用“afirmatives.contains”部分替换了我所拥有的,它清除了那个错误。当我添加“使用 System.Linq”时,它给了我另一个我开始尝试理解的单独错误。我开始擦除它并返回到我的原始代码,但注意到在我取出“使用 System.Linq”后,我的所有错误都消失了,代码按预期工作。谢谢!!!我不确定它为什么现在有效而以前无效,但我相信我很快就会学会。
  • 是的,对不起。 using System.Linq; 必须位于顶部,在课堂或课程之外,通常靠近 using System;
猜你喜欢
  • 2011-03-29
  • 2018-08-25
  • 2020-09-20
  • 2021-12-14
  • 2016-01-25
  • 2017-09-03
  • 2010-11-16
  • 2015-09-08
相关资源
最近更新 更多