How to get the extra character from two strings in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_map>

char getExtraCharacter(std::string str1, std::string str2) {
   std::unordered_map<char, int> umap;
   
   for (int i = 0; i < str2.length(); i++)
      umap[str2[i]]++;
      
   for (int i = 0; i < str1.length(); i++)
      umap[str1[i]]--;
      
   for (auto item = umap.begin(); item != umap.end(); item++) {
        if (item->second == 1) // ++ --
            return item->first;
   }
   
   return -1;
}


int main() {
   std::string str1 = "CJAVA";
   std::string str2 = "CJAXVA";
   
   std::cout << getExtraCharacter(str1, str2);
}




/*
run:

X

*/

 



answered Dec 6, 2022 by avibootz

Related questions

2 answers 221 views
1 answer 164 views
3 answers 212 views
1 answer 130 views
1 answer 121 views
1 answer 115 views
1 answer 138 views
...