使用 c# 或 javascript 比较两个字符串数组

本文关键字:两个 字符串 数组 javascript 比较 使用 | 更新日期: 2023-09-27 18:31:29

我有两个字符串数组名称str_arr1[],str_arr2[]。具有相同或不同值的两个数组。

str_arr1[] = { "one", "two", "three","four","Doctor","Engineer","Driver" };
str_arr2[] = { "one", "Doctor","Engineer" };

通常str_arr1[] 与 str_arr2[] 相比,记录更多。我想检查str_arr1[]是否具有str_arr2[]。如果它是真的,则意味着返回真。否则返回 false。

使用 c# 或 javascript 比较两个字符串数组

bool contains = !str_arr2.Except(str_arr1).Any();
function compareArrays(arr1, arr2) {
  if (arr1.length != arr2.length) {
    return false;
  }
  return arr1.sort().join() == arr2.sort().join();
}
var arr1 = ["one", "two", "three","four","Doctor","Engineer","Driver" ];
var arr2 = ["one", "Doctor","Engineer"];
    console.log(compareArrays(arr1,arr2));

请使用这个

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1,a2))
        return true;
    if (a1 == null || a2 == null)
        return false;
    if (a1.Length != a2.Length)
        return false;
    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}
bool result=str_arr2.Any(x=>!str_arr1.Contains(x));
var str_arr1 = new string[] { "one", "two", "three", "four", "Doctor", "Engineer", "Driver" };
        var str_arr2 = new string[] { "one", "Doctor", "Engineer" };
        return str_arr1.Intersect(str_arr2).Count() == str_arr2.Length;
var inter = str_arr1.Intersect( str_arr2);
foreach (var s in inter)
{
    Console.WriteLine("present" + s); // or you can return somthin
}

您没有清除条件。我正在结合其中的所有条件。

 string[] str_arr1 = new string[] { "one", "two", "three", "four", "Doctor", "Engineer", "Driver" };
 string[] str_arr2 = new string[] { "one", "aaaa", "yyy" };
 bool contains = !str_arr2.Except(str_arr1).Any(); // this will show true only if all the items of str_arr2 are in str_arr1 
 bool result = str_arr2.Any(x => !str_arr1.Contains(x));// this will show true if any of the items of str_arr2 are in str_arr1