Home > database >  comparing two arrays to find matched words
comparing two arrays to find matched words

Time:10-18

So i've made a successful attempt of web scraping all the articles from a website and store them inside an array.

The issue however, is that the matched words are not found or pretty much fails to increase a variable showing how many articles share the same matched word.

What i've got so far is this

string[] feed = doc.DocumentNode.SelectNodes("//h2[@class='entry__title']").Select(t => t.InnerText).ToArray();
string[] word = { "covid" };
int matchedWords = 0;
            
for(int i = 0; i < feed.Length; i  )
{
   for(int j = 0; j < word.Length; j  )
   {
       if (feed[i] == word[j])
       {
            matchedWords;
       }
   }
}

CodePudding user response:

try this:

string[] feed = doc.DocumentNode.SelectNodes("//h2[@class='entry__title']").Select(t => t.InnerText).ToArray();
        string[] word = { "covid" };
        int matchedWords = 0;

        for (int i = 0; i < feed.Length; i  )
        {
            for (int j = 0; j < word.Length; j  )
            {
                if (feed[i].ToLower().Contains(word[j].ToLower()) == true)
                {
                    matchedWords  ;
                }
            }
        }

CodePudding user response:

You can run a for loop for first array and add the add the items to a Dictionary with key as item.

Initialise a count variable, And then run a for loop for the second array and check if the key is present is the Dictionary. If it’s present then increase the count variable.

variable count will tell you the common items between two arrays.

You should handle for duplicates also.

  • Related