To compare two strings and remove the same characters from string 1 and print the string 2 using C++
I am a newbie in programing and stuck at a point where I have to compare the two strings using C++: string 1 and string 2 for the same characters and then delete those characters from string 1 and print the string 2. Looking forward for your help. My code goes like this:
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
string first_string;
string second_string;
string::size_type start_position=0;
cout<<"Please enter the first string: "<<endl;
getline(cin,first_string);
cout<<"Please enter the Second string: "<<endl;
getline(cin, second_string);
while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
while ( (start_position = second_string.find(first_string, start_position)) != string::npos )
{
second_string.replace( st开发者_C百科art_position, first_string.size(), "" );
start_position++;
}
}
cout<<"The Result is as follws: "<<second_string<<endl;
getch();
return 0;
}
Looking forward for your help.
Regards, Sam
Compare each char in string2 with all chars of string1. If that char from string2 doesn't match any in string1 then append this char to a new string else continue without appending. Continue this for all chars in string2. Now assign the new string as string1. This uses extra o(n) space but is simpler.
I would recommend using c_str to represent your string as an array of characters (or even better begin with an array of characters rather than the string datatype). After you do this write a function to go through each array and compare characters (removing where required), its a bit inefficient but it'll do the job and its simple.
精彩评论