Find common characters Given two strings, find the common characters.


Is there better implementation for this problem?

#include&lt;iostream&gt;
#include&lt;string&gt;
#include&lt;algorithm&gt;

std::string   find_intersection(std::string &amp; first, std::string &amp; second)
{
   std::sort(std::begin(first),std::end(first));
   std::sort(std::begin(second), std::end(second));
   int length = std::min(first.length(), second.length());
   std::string result(length,' ');
   std::set_intersection(std::begin(first),std::end(first),std::begin(second),std::end(second),std::begin(result));

   result.shrink_to_fit();
   return result; 
}

int main()
{
   std::string first="GermanTown";
   std::string second="Georgia";
    std::cout&lt;&lt;find_intersection(first,second)&lt;&lt;"\n";
   return 0;
}
For the same reasons as @DJanssens, I would like to compliment you for a simple and clean algorithm making proper use of the standard library. That may seem basic, but there are too many people ignoring the standard &lt;algorithm&gt; in the world, so I'm glad that you decided to use it. I only want to add two more things:


First, I don't think that shrink_to_fit will do what you expect it to do. When you construct result, you allocate memory and fill it with spaces, so result's size probably grew to. shrink_to_fit will get rid of the allocated but unused memory, but it won't get rid of the extra spaces that you allocated at construction.
What you can do is default-construct your std::string and use an std::back_inserter to fill it the lazy way. The std::back_inserter will perform some magic so that the result's push_back method is called whenever an element has to be added:

std::string find_intersection(std::string &amp; first, std::string &amp; second)
{
    std::sort(std::begin(first),std::end(first));
    std::sort(std::begin(second), std::end(second));

    std::string result;

    std::set_intersection(
        std::begin(first), std::end(first),
        std::begin(second), std::end(second),
        std::back_inserter(result)
    );

    return result; 
}