CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Apr 2004
    Posts
    123

    Comparing two string arrays?

    Hi,

    How do i compare two string arrays efficiently in .NET 2.0..??

    I have two arrays like given below..
    Code:
    string[] brokers1 = new string[]{"john","andy",Mitchel","Harry"};
    string[] brokers2 = new string[]{"andy","john","Harry","Mitchel"};
    Following conditions should return false:
    1)If the length of arrays differ
    2)If the elements in the arrays differ

    Should return true for the following conditions:
    1)If both the arrays are having the same length and has the same string elements,even though present at different indexes.

    How do i compare both of them efficiently.Is there a built in mechanism for comparing them?Or does some one know an efficient and clean code for this?

    Thanks in advance,
    Mmx

  2. #2
    Join Date
    May 2007
    Posts
    1,546

    Re: Comparing two string arrays?

    Code:
    public static bool ByteMatch(byte[] array1, byte[] array2)
            {
                if (array1.Length != array2.Length)      // If the arrays are different lengths, then they are not equal
                    return false;
    
                return ByteMatch(array1, array2, 0, 0, array1.Length);
            }
    
            public static bool ByteMatch(byte[] array1, byte[] array2, int offset1, int offset2, int count)
            {
                if (array1 == null)
                    throw new ArgumentNullException("array1");
                if(array2 == null)
                    throw new ArgumentNullException("array2");
    
                for (int i = 0; i < count; i++)
                    if (array1[offset1 + i] != array2[offset2 + i]) // For each element, if it is not the same in both
                        return false;                               // arrays, return false
    
                return true;                            // If we get here, all the elements matched, so they are equal
            }
    Something like the above should work fine. It takes two array's and makes sure that 'count' number of elements starting at offset1 in array1 equal the same in array2 starting at offset2.

    The other overload just takes 2 arrays and checks them for length equality first, then member equality.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  3. #3
    Join Date
    Jul 2003
    Location
    Bali, Indonesia
    Posts
    103

    Re: Comparing two string arrays?

    If you working in .Net framework3.0 that already have LinQ you can use the extended method of contain in Array class.
    You can improve your code using Generic Method so you can compare not just array of string but all IComparable implementation.

    If you dont have the LinQ you may convert the array to the List<T> then you can explore it

    Code:
    private static bool CompareArray(string[]  arr1, string[] arr2)
            {
                //see the length
                if(arr1.Length != arr2.Length)
                {
                    return false;
                }
    
                //iterate throught it
                foreach( string str in arr1 )
                {
                    if(!arr2.Contains( str ))
                    {
                        return false;
                    }
                }
    
                return true;
            }

  4. #4
    Join Date
    Apr 2004
    Posts
    123

    Re: Comparing two string arrays?

    Will i get a generic version of what mutant fruit has given here???

    The requirement is that,i have to compare both string arrays as well as datetime arrays.

    Thanks,
    Mmx

  5. #5
    Join Date
    Apr 2004
    Posts
    123

    Re: Comparing two string arrays?

    How do i convert a string[] or a datetime[] to a byte[]..???

  6. #6
    Join Date
    Jul 2003
    Location
    Bali, Indonesia
    Posts
    103

    Re: Comparing two string arrays?

    If you use generic method you don`t need to use any converter.
    I also put some additional comment, I hope this will help.

    Code:
    private static bool CompareArray<T>(T[]  arr1, T[] arr2)
            {
                //see the length
                if(arr1.Length != arr2.Length)
                {
                    return false;
                }
    
                //iterate throught it
                foreach( T str in arr1 )
                {
                    //Is the arr2 have the same value in any index?
                    //So it is doesn`t matter in what index the value exist
                    if(!arr2.Contains( str ))
                    {
                        //if not, return false
                        return false;
                    }
                }
                //all value in arr1 also exist in arr2
                return true;
            }
    I only change the type from string to T . You can try it... it work in my place

  7. #7
    Join Date
    May 2007
    Posts
    1,546

    Re: Comparing two string arrays?

    In my code (which is .NET 2.0+ compatible) you just change the declarations some like as follows:

    public static bool ArrayMatch<T>(T[] array1, T[] array2)

    And rename 'byte' to 'T' inside the method bodies. That makes it 'generic'. The other thing is that when comparing the elements you should use .Equals() rather than ==.

    Generally speaking, .Equals() gives value equality (i.e. two objects have the same value) and == gives reference equality (the two objects are the same instance).
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  8. #8
    Join Date
    Jan 2007
    Posts
    491

    Re: Comparing two string arrays?

    Quote Originally Posted by saktya
    If you working in .Net framework3.0 that already have LinQ you can use the extended method of contain in Array class.
    You can improve your code using Generic Method so you can compare not just array of string but all IComparable implementation.

    If you dont have the LinQ you may convert the array to the List<T> then you can explore it

    Code:
    private static bool CompareArray(string[]  arr1, string[] arr2)
            {
                //see the length
                if(arr1.Length != arr2.Length)
                {
                    return false;
                }
    
                //iterate throught it
                foreach( string str in arr1 )
                {
                    if(!arr2.Contains( str ))
                    {
                        return false;
                    }
                }
    
                return true;
            }
    Yea well... But that will return true also in case like that:
    "john","anna","john","john"
    "anna", "john", "anna", "john"
    And it's not exactly the same...
    That would do:
    Code:
    private bool compareStringArrays(string[] arr1, string arr2[])
    {
            int length;
            bool found = false;
            if(arr1.Length != arr2.Length) return false;
            length = arr1.Length;
            for(int i = 0; i < length; i++)
            {
                    for(int j = 0; j < length; j++)
                    {
                            if(arr[j] != null && arr[i] != null && arr1[i] == arr2[j])
                            {
                                    arr2[j] = null;
                                    found = true;
                                    break;
                            }
                    }
                    if(!found) return false;
                    found = false;
            }
            return true;
    }
    It's not as fast as the codes above, but it will do what you need.

    If you'll use it make sure that there is no "null" value in one of the elements of the arrays before calling this function. otherwise it'll just return false.

    I didn't check the code. It should work, though.

    HTH, Tal.
    Last edited by Talikag; October 12th, 2007 at 10:42 AM.

  9. #9
    Join Date
    Apr 2004
    Posts
    123

    Re: Comparing two string arrays?

    I tried mutant fruits code...guess what....Equals() on same string is returning false and cant use == when using generic<T>.It throws out an error.Any quick fixes to this??

  10. #10
    Join Date
    Apr 2004
    Posts
    123

    Re: Comparing two string arrays?

    Hey guys...

    It was a mistake in my code...all the code posted above works fine...Thanx a ton!!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured