检查数组中的每个元素以查看其是否等于字符串

时间:2019-06-09 05:07:17

标签: c# arrays string-comparison

我在数组中有许多元素,我想检查字符串是否等于数组中的任何这些元素。数组中元素的数量可以改变。

我已经计算了数组中的元素数量,希望获得某种优势,但是还没有提出解决方案。

int ArrayCount = FinalEncryptText.Count();
foreach (string i in FinalEncryptText)
                {
                }

3 个答案:

答案 0 :(得分:1)

使用您提供的foreach实现,可以在String.Equals()中包含if条件-如Sean所述。但是,值得注意的是,没有参数的String.Equals()等同于使用==运算符。最好指定StringComparison类型。

例如,您可以使用以下内容:

foreach(string element in myStringArray)
{
   if(element.Equals("someString", StringComparison.CurrentCultureIgnoreCase))
     ...
}

您可以了解有关比较字符串here的更多信息。

答案 1 :(得分:0)

您可以在if语句中使用String.Equals方法。有关String.Method的更多信息,请访问:https://docs.microsoft.com/en-us/dotnet/api/system.string.equals?view=netframework-4.8

if(firstString.Equals(secondString))
{
    //whatever you need to do here
}

答案 2 :(得分:0)

我不确定您的方法是什么样子,但是我假设..给您一个随机的字符串数组..并且您想在该数组中找到某个元素。使用foreach循环:

public string Check(string[] FinalEncryptText)
{
    foreach (string i in FinalEncryptText)
    {
       //let's say the word you want to match in that array is "whatever"
        if (i == "whatever")
        {
             return "Found the match: " + i;
        }
    }
}

使用常规的for循环:

public string Check(string[] FinalEncryptText)
{
    for (int i = 0; i < FinalEncryptText.Count; i++)
    {
       //let's say the word you want to match in that array is "whatever"
        if (FinalEncryptText[i] == "whatever")
        {
             //Do Something
             return "Found the match: " + FinalEncryptText[i];
        }
    }
}

现在,如果您已经有一个固定的数组..并且您要传递一个字符串来检查该字符串是否存在于数组中,那么它将变成这样:

public string Check(string stringToMatch)
{
    for (int i = 0; i < FinalEncryptText.Count; i++)
    {
       //this will match whatever string you pass into the parameter
        if (FinalEncryptText[i] == stringToMatch)
        {
             //Do Something
             return "Found the match: " + FinalEncryptText[i];
        }
    }
}