union of two strings A and B

I need to write the function which return the union of two strings in C++.

1
2
3
4
5
public string union(string A, string B)
{
   code

}


Could someone help me how to write the code?
return A+B; unless you mean something else by union..
example

string A="Programing"

string B="Program"

union is string C ="Programing"
Well, that's just picking the longer one.
what is union("hello", "world") ?

If you really mean a union of sets, then you could look into std::set class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <iostream>
using namespace std;
int main(){
    string s1="123"; //Set up string 1
    string s2="456"; //Set up string 2
    string s3;       //Setup string 3
 
    cout<<"First  string: "<<s1<<endl;
    cout<<"Second string: "<<s2<<endl;
    s3=s1;           //Copy string 1 into string 3
    for(int i=0;i<s2.size();i++){        //Loop through s2
        char c=s2[i]; //Grab current character from s2
        bool is_c_in_s3=true;
        for(int j=0;j<s3.size();j++){    //Loop though s3
            cout<<"Figure this portion out yourself."<<endl;
        }
        if(is_c_in_s3){
            s3+=c; //Add the element to String 3
        }
    }
    cout<<"Final string: "<<s3<<endl;
}




I try to solve with this code, but I need help how to fixed this code, if you know help it is very important
The bit of code you lack is surely meant to change or keep is_c_in_s3. Surely it is if(/*some condition*/) is_c_in_s3=false;. You really need to figure that condition out yourself. It's to understand the basics of loops.
Note, also, that the name is_c_in_s3 is misleading. In a union operation, you only need to add an element if it isn't present yet.
could you help how to do this in my code, if you know...
Ahh. Fine.
if(s3[j] == c) is_c_in_s3 = false;
You are too generous, hamsterman
cout<<"Figure this portion out yourself."<<endl;

union is string C ="Programing"
The 'g' and the 'r' are repeated...
@ne555, I'm hardly in any kind of position to enforce learning.
Topic archived. No new replies allowed.