I am programming in C++ and am attempting to find the intersection of two strings, only the items common to both and thus return a third string with these items. Essentially, I am trying to write
the code for the STL library set_intersection.
To approach this problem I thought of I can use two nested loops one loop to cycle thru each string. Then having a variable to compare values in common, which means I would
have to have a temp variable to store common elements.
something similar to this:

string names[] = {"AMC", "ANZ", "AMX"};            
 for( int i = 0; i < 3; i++ ) {
   for( int j = 0; j < 3; j++ ) {
     cout << names[i].compare(names[j] ) << " ";
   cout << endl;

Any further sugestions would be great,

Recommended Answers

All 10 Replies

the compare() function is not what you need. It only tells you whether one string is the same as the other. you need to check the two strings one character at a time and create a third string that contains the characters which are in both strings. For example, the first two strings have the letters 'A' and 'M' in both strings, so a third string will contain "AM".

How does one check each char at a time? As you can see, i've only had success at comparing a whole string. Thanks

you can use a loop. Something like below. The find() method will search one string for an instance of another string and return the position where its at.

string str1 = "ABC";
string str2 = "BCD";
string result;

for(int i = 0; i < str2.length(); ++)
   if( str1.find( str2[i] ) != string::npos )
       result += str2[i];

Fantastic, gr8 help Ancient Dragon. After 8hrs of sitting behind this screen your saviour was lifeline!

You should also look at this ;)

nicko, thats my post. thanks anywayy

nicko, thats my post. thanks anywayy

Your solution was nearly identicale to mine except your made a check to insure duplicates are not inserted into the new string. If you already knew the solution why did you post the question in this thread?:eek: :?: :rolleyes:

because that is dealing wih strings i want to adapt it to handle vectors

now you are asking a completly different question. vectors of what? strings? do you want to create a vector that is a union of two other vectors, where each string in the new vector is the union of the corresponding strings in two or more other vectors? The algorithm would be almost identical to what has already been posted.

nicko, thats my post. thanks anywayy

Yes, I know. That was my answer!

P.S. You should distinct union and intersection
And one more thing, I'm Micko, not nicko :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.