Home > Software design >  Compare string array1 with string array2 and return entries that are not present in array2
Compare string array1 with string array2 and return entries that are not present in array2

Time:11-14

I have two arrays in my C code. array1 has all elements but array2 has the same elements but with a few missing. I am trying to find out the elements that are missing in array2. Instead of showing the missing elements, it is showing elements which are also present in both the arrays and multiple times.

string array1[] = { "aaa","bbb","ccc","ddd" };
string array2[] = { "aaa","bbb","ccc" };

for (i = 0; i <= 3; i  )
{
    for (int j = 0; j <= 2; j  )
    {
        if (array1[i] == array2[j])
            continue;
        else
            cout << array1[i] << endl;
    }
}

'''

enter image description here

I tried using nested for loops to try to compare every element from array1 with all the elements of array2. If a match is found, the loop is supposed to skip and move on to the next iteration and if a match has not been found, it should display the element that was not found in array2.

CodePudding user response:

You implemented the logic of your code a little bit wrong.

So, first iterate over all elements from array1.

Then, check, if the current element is in the array2. For this you can use a flag.

If it is not in, then print it.

There are even standard functions in the C algorithm library availabe.

But let's ge with the below solution:

#include <iostream>
#include <string>

using namespace std;


int main() {
    string array1[] = { "aaa","bbb","ccc","ddd" };
    string array2[] = { "aaa","bbb","ccc" };

    for (int i = 0; i <= 3; i  )
    {
        bool isPresent = false;
        for (int j = 0; j <= 2; j  )   
            if (array1[i] == array2[j]) 
                isPresent = true;

        if (not isPresent)
            std::cout << array1[i] << '\n';
    }
}

CodePudding user response:

Your code is working exactly what you write but not as your expectation. Let analysis it. If you take aaa from array1, it will compare with all string of array2, then it it will:

first element of array2: aaa -> continue
second element of array2: bbb -> print aaa
third element of array2: ccc -> print aaa

And so on. You need to improve your logic thinking than requesting us to check your code.

  • Related