如何将一个字符串数组的每个元素与另一个字符串数组的每个元素进行比较?

时间:2012-07-15 12:29:53

标签: c# arrays string

我有两个字符串数组。我想从第一个数组中选择一个元素并与第二个数组的每个元素进行比较。如果来自第一个数组的元素存在于第二个数组的元素中,我想写一个例子(“元素存在”)或类似的东西。

这应该可以用两个for循环吗?

修改

好的,我最终想要使用这个代码:

string[] ArrayA = { "dog", "cat", "test", "ultra", "czkaka", "laka","kate" };
string[] ArrayB = { "what", "car", "test", "laka","laska","kate" };

bool foundSwith = false;

for (int i = 0; i < ArrayA.Length; i++)
{

   for (int j = 0; j < ArrayB.Length; j++)
   {
       if (ArrayA[i].Equals(ArrayB[j]))
       {
           foundSwith = true;
           Console.WriteLine("arrayA element: " + ArrayA[i] + " was FOUND in arrayB");
       }
   }

   if (foundSwith == false)
   {
      Console.WriteLine("arrayA element: " + ArrayA[i] + " was NOT found in arrayB");
   }
   foundSwith = false;
}

我希望这会帮助那些想要比较两个数组的人;)。这一切都是关于这个发现的开关。请再次寻求帮助。

3 个答案:

答案 0 :(得分:4)

foreach (string str in yourFirstArray)
{
   if (yourSearchedArray.Contains(str))
   {
      Console.WriteLine("Exists");
   }
}

答案 1 :(得分:1)

foreach (string str in strArray)
{
   foreach (string str2 in strArray2)
   {
       if (str == str2)
       {
          Console.WriteLine("element exists");
       }
   }
}

更新为在strArray2

中不存在字符串时显示
bool matchFound = false;
foreach (string str in strArray)
    {
       foreach (string str2 in strArray2)
       {
           if (str == str2)
           {
              matchFound = true;
              Console.WriteLine("a match has been found");
           }
       }

       if (matchFound == false)
       {
          Console.WriteLine("no match found");
       }
    }

或者用更少的代码行完成另一种方式:

foreach (string str in strArray)
{
    if(strArray2.Contains(str))
    {
       Console.WriteLine("a match has been found");
    }
    else
    {
       Console.WriteLine("no match found");
    }
}

答案 2 :(得分:-1)

您也可以尝试:

ArrayA.All(ArrayB.Contains);