比较两个 NSArray 并返回差异数

发布于 2024-09-03 16:22:03 字数 131 浏览 4 评论 0原文

如何获取两个 NSArray,比较它们,然后返回差异的数量,最好是不同对象的数量,例如:

数组 1: 一 二 三个

数组2: 二 四 我

希望返回“1”

How can I take two NSArrays, compare them, then return the number of differences, preferably the number of different objects, for example:

Array 1:
one
two
three

Array 2:
two
four
one

I would like that to return "1"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉世弥音 2024-09-10 16:22:03

您可以使用中间 NSMutableArray

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Four", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

这样,只会删除公共元素。

You can do this by using an intermediate NSMutableArray:

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Four", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

With that way, only common elements will be removed.

七度光 2024-09-10 16:22:03

我发现上面的答案没有考虑不同大小的数组。如果你按照上面的方法做,你应该检查哪个 array.count 更小,

[largerArray removeObjectsInArray:shorterArray];

或者

我将它们都设置为 NSSet,然后进行比较。

[set1 isEqualToSet:set2];

这样尺寸和顺序都得到正确处理! (我不需要知道差异的数量)

I found that the answer above didn't take arrays of differing size into account. If you do it as above, you should check to see which array.count is smaller and

[largerArray removeObjectsInArray:shorterArray];

OR

I made them both NSSets and then compared.

[set1 isEqualToSet:set2];

That way size and order are both dealt with properly! (I didn't need to know the number of differences)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文