How to find and print the common characters (letters) in different strings with C++

3 Answers

0 votes
#include <iostream>
#include <string>
#include <set>

std::string getCommonCharacters(std::string str1, std::string str2) {
    std::string strcommon = "";
     
    int str1size = str1.length();
    int str2size = str2.length();
     
    for (int i = 0; i < str1size; i++) {
        for (int j = 0; j < str2size; j++) {
            if (str1[i] == str2[j] && str1[i] != ' ')
                strcommon += str1[i];
        }
    }
     
    std::set<char> unique(strcommon.begin(), strcommon.end());
    strcommon.assign(unique.begin(), unique.end()); 
    
    return strcommon;
}
 
int main(void) {
    std::string str1 = "c c++ c# java go";
    std::string str2 = "python nodejs php javascript";
    
    std::string strcommon = getCommonCharacters(str1, str2);
    
    std::cout << "Same letters are: " << strcommon << std::endl;
}
    
 
 
 
/*
run:
 
Same letters are: acjov
 
*/

 



answered Jan 24, 2024 by avibootz
edited Jan 26, 2024 by avibootz
0 votes
#include <algorithm>
#include <iostream>
#include <string>
#include <set>

std::string getCommonCharacters(std::string str1, std::string str2) {
    std::string strcommon = "";
      
    std::set<char> s1(str1.begin(), str1.end()), s2(str2.begin(), str2.end());
    set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(strcommon));
    
    return strcommon;
}
 
int main(void) {
    std::string str1 = "c c++ c# java go";
    std::string str2 = "python nodejs php javascript";
    
    std::string strcommon = getCommonCharacters(str1, str2);
    
    std::cout << "Same letters are: " << strcommon << std::endl;
}
    
 
 
 
/*
run:
 
Same letters are:  acjov
 
*/

 



answered Jan 24, 2024 by avibootz
edited Jan 26, 2024 by avibootz
0 votes
#include <unordered_set>
#include <iostream>
#include <string>

std::string getCommonCharacters(std::string str1, std::string str2) {
    std::string strcommon = "";
      
    int str2size = str2.length();
     
    std::unordered_set<char> s1(str1.begin(), str1.end()), s2;
     
    for (size_t i = 0; i < str2size; ++i) {
        if (s1.count(str2[i])) {
            s2.insert(str2[i]);
        }
    }
            
    strcommon.assign(s2.begin(), s2.end());
    
    return strcommon;
}
 
int main(void) {
    std::string str1 = "c c++ c# java go";
    std::string str2 = "python nodejs php javascript";
    
    std::string strcommon = getCommonCharacters(str1, str2);
    
    std::cout << "Same letters are: " << strcommon << std::endl;
}
    
 
 
 
/*
run:
 
Same letters are: cvja o
 
*/

 



answered Jan 24, 2024 by avibootz
edited Jan 26, 2024 by avibootz
...