1

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,
Thanks,
I

3
Contributors
10
Replies
11
Views
10 Years
Discussion Span
Last Post by Micko
0

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".

1

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

0

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];
}
1

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

0

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:

1

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.