1

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

这应该可以用两个 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;
}

我希望这将有助于其他想要比较两个数组的人;)。这一切都与这个foundSwitch有关。Thx 再次寻求帮助。

4

3 回答 3

5
foreach (string str in yourFirstArray)
{
   if (yourSearchedArray.Contains(str))
   {
      Console.WriteLine("Exists");
   }
}
于 2012-07-15T12:33:23.113 回答
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");
    }
}
于 2012-07-15T12:33:52.170 回答
-1

You can also try:

ArrayA.All(ArrayB.Contains);
于 2014-12-15T03:00:58.747 回答