如何比较两个字符串数组? [英] How to compare two arrays of string?

查看:553
本文介绍了如何比较两个字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个字符串数组.我不知道如何在vb.net中实现这一点.

I want to compare two string arrays. I don't know how to implement this in vb.net.

假设我有两个数组

Dim A() As String = {"Hello", "How", "Are", "You?")
Dim B() As String = {"You", "How", "Something Else", "You")

我想将A()与B()进行比较,以了解它们之间的异同(元素的顺序无关紧要,这意味着程序不检查元素的顺序,仅在存在的情况下进行比较是相同的元素). 同样,代码将忽略同一字符串数组中的相同元素(如数组B()中的第二个"You"),然后代码将返回这些元素相同但元素不同的情况.在这种情况下,输出消息应是:

And I want to compare A() with B() to see how they are similar and different (The order of the elements does not matter, which means the program does not check the order of the elements and only compares if there are same elements). Also the code would ignore the same elements in the same string array(like the second "You" in array B(). Then the code would return the elements these are same and the elements those are different. In this case the output message should be:

相同的元素是您"和如何"

The same elements are "You" and "How"

另一个元素是其他东西"

The different element is "Something Else"

推荐答案

对于Linq,使用Except()查找两个数组之间的差异,并使用Intersect()查找两个数组中的元素.

With Linq use Except() to find the differences between the two arrays and Intersect() to find which elements are in both arrays.

Imports System.Linq

Module Module1
    Sub Main()
        Dim A() As String = {"Hello", "How", "Are", "You?"}
        Dim B() As String = {"You", "How", "Something Else", "You"}

        Console.WriteLine("A elements not in B: " + String.Join(", ", A.Except(B)))
        Console.WriteLine("B elements not in A: " + String.Join(", ", B.Except(A)))
        Console.WriteLine("Elements in both A & B: " + String.Join(", ", A.Intersect(B)))

        Console.ReadLine()
    End Sub
End Module

结果:

A elements not in B: Hello, Are, You?
B elements not in A: You, Something Else
Elements in both A & B: How

这篇关于如何比较两个字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆