Hi Guys Im trying to check if the string have all the same characters or not
if it is same i want to print it out, can some one tell me whats wrong below
bool homogenous( const std::string& word )
{
if ( word.empty() ) returnfalse; // or true, up to you
auto it = word.begin();
char token = *it;
++it;
return std::all_of( it, word.end(), [token](char c){return c==token;} );
}
Simple pieces can then be used with many words.
1 2 3 4
vector<string> text;
for ( auto w : text ) {
if ( homogenous(w) ) std::cout << w << '\n';
}
Zaap, your comparing characters in the same word. That tell you if two words contain the same characters.
The tricky part to this problem is that you have to account for the number of occurences of the letters, not just whether the letters from one word appear in the other. A really simple way to do this is to sort the words and then compare them.
#include <string>
#include <iostream>
#include <algorithm>
usingnamespace std;
bool sameChars(string word1, string word2)
{
sort(word1.begin(), word1.end());
sort(word2.begin(), word2.end());
return (word1 == word2);
}
int main()
{
string str1, str2;
while (cin >> str1 >> str2) {
cout << str1
<< (sameChars(str1, str2) ? " does " : " does not ")
<< "contain the same characters as " << str2 << '\n';
}
}
That runs in O(n*log(n)) time where n in the size of a word. A theoretically faster way is to create an array that counts the letters of each word and then compare the arrays. That runs in O(n) time, but words in human language are small and I suspect that the first method will outperform the second in practical applications.