繁体   English   中英

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

[英]How can I compare each element of one string array to every element of another string array?

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

这应该可以用于两个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有关。 再次寻求帮助。

foreach (string str in yourFirstArray)
{
   if (yourSearchedArray.Contains(str))
   {
      Console.WriteLine("Exists");
   }
}
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");
    }
}

您也可以尝试:

ArrayA.All(ArrayB.Contains);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM