Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# comparision arrays
I have two string arrays, one bigger than the other, and i need to check if any of the strings in the arrays are the same.
Posted 9-Mar-12 0:00am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

My preferred method would be to sort each array.
Then just compare with a single loop:
If (string A > string B)
   move B
else if (string A < string B)
   move A
else 
   Same - record, and move A and B.
You can use Array.Sort to sort string arrays into order:
string[] st = new string[] { "qwertyuiop", "asdfghjkl", "zxcvbnm" };
Array.Sort(st);
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Try this:
string[] array1, array2;
//list to store index's of same strings
List<keyvaluepair><int,int>> couplesList = new List<keyvaluepair><int,int>>();
 
//array creation goes here

//the algorithm 
for(int i = 0; i < array1.Length; i++)
{
    for(int j = 0; j < array2.Length; j++)
    {
        if(array1[i] == array2[j])
        {
           couplesList.Add(new KeyValuePair<int,int>(i,j));
        }
    }
}</keyvaluepair></keyvaluepair>
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

I wud have done something like this:
 
//smaller is the array with less no. of strings
//bigger is the array with more no. of strings

//this loop compares if any string in smaller is present in bigger
foreach(string i in smaller)
foreach(string j in bigger)
{
if(i==j)
Console.WriteLIne(i);//print the common string
}
 
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

A LINQ solution:
string[] test = new string[] { "one", "two", "three" };
string[] test1 = new string[] { "four", "six", "eight", "ten", "one" };
 
string[] result = test.Intersect(test1).ToArray();
 
result contains the strings that are the same in both arrays.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web04 | 2.8.150302.1 | Last Updated 9 Mar 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100