如何检查字符串数组中是否包含字符串?

时间:2020-10-31 03:30:27

标签: c#

我要花大约0的先验编码知识来学习C#。有人可以告诉我为什么这行不通吗?

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();

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

我是否必须制作多条其他线?

谢谢!

修改

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();

1 个答案:

答案 0 :(得分: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是测试数组或列表是否包含值的简便方法