Hi, I want to make a function which does the following:
take two strings, str1 and str2. Check if all the characters of one string are contained in the other string. I want to solve this problem using iterators, so here is my code:
#include <iostream>
#include <algorithm>
#include <string>
usingnamespace std;
bool is_subsequence(string& str1, string& str2)
{
string tmp; // check that str1 is the smaller string, to see if str1 is contained in str2
if (str1.length() > str2.length())
{
tmp = str1;
str1 = str2;
str2 = tmp;
}
sort(str1.begin(), str1.end()); // sort both strings
// to check if str1 is inside str2 sequentially
sort(str2.begin(), str2.end());
typedef string::iterator iter;
iter j = str2.begin();
iter i = str1.begin();
while (i != str1.end())
{
j = find(j, str2.end(), *i);
}
if (j != str2.end())
returntrue;
returnfalse;
}
int main()
{
cout << "Please enter two strings " << endl;
string s1, s2;
(cin >> s1);
(cin >> s2);
cout << "Is s1 contained in s2?? 0=no, 1=yes" <<is_subsequence(s1,s2) <<endl;
return 0;
}
The problem is that I enter the two strings and press enter, but the compiler does nothing, i.e. cursor flashes but program doesn't compile nor allows me to do anything so I have just abruptly closed the window... what's going on???
My problem is to figure out if I have played correctly with the iterators and the find function.
The while loop on line 26 will either end immediately (str1.begin() == str1.end()) or never since i will not be changed within the loop. A for loop or range based loop for is better in this case.
Further more the loop should end (maybe with a break) if j == str2.end()
j is never incremented and so this will always return true and it is not clear what is the purpose of this block of code
1 2 3
string s1, s2;
(cin >> s1);
(cin >> s2);
as already mentioned on another thread, this is erroneous and stumbles on whitespace, use getline() instead
cout << "Is s1 contained in s2?? 0=no, 1=yes <<is_subsequence(s1,s2) <<endl;
there's a missing " after "yes" and there is no previous check that s1.size() is <= s2.size(). In fact, as you're trying to
(c)heck if all the characters of one string are contained in the other string
, the string with the larger number of unique (edit: ?) characters should be the parent string and the other string should be the child string and then you check if a child is a sub-set of the parent
Hi coder777, yes, thanks once more. In fact I had already implemented the break instruction within the loop, so the first time that j reached str2.end() the program already stops, avoiding the unnecessary check for all the other characters of str1. Thanks again!