How to check whether two strings contain same characters in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    string s1 = "c++ programming";
    string s2 = "progingramm c++";
    
    sort(s1.begin(), s1.end());
    sort(s2.begin(), s2.end());
    
    if (s2 == s2)
        cout << "yes";
    else
        cout << "no";
}


/*
run:

yes

*/

 



answered Oct 26, 2019 by avibootz
0 votes
#include <bits/stdc++.h> 
  
using namespace std; 
 
string remove_duplicate_characters(string s) {
    sort(s.begin(), s.end()); 
    
    auto no_dup = unique(s.begin(), s.end()); 
  
    s = string(s.begin(), no_dup);
     
    return s;
}

bool contain_same_characters(string s1, string s2) {
    string s1_tmp = remove_duplicate_characters(s1);
    string s2_tmp = remove_duplicate_characters(s2);
      
    sort(s1_tmp.begin(), s1_tmp.end());
    sort(s2_tmp.begin(), s2_tmp.end());
    
    if (s1_tmp == s2_tmp)
        return true;
        
    return false;
}
    
int main() 
{ 
    string s1 = "c++ programming";
    string s2 = "proooogggingrammmm c++";
     
    if (contain_same_characters(s1, s2))
        cout << "yes";
    else
        cout << "no";
 
    return 0; 
} 
  
  
  
/*
run:
  
yes
   
*/

 



answered Oct 27, 2019 by avibootz
edited Oct 29, 2019 by avibootz
...