Find common characters from group of string

Find common characters from group of string

Problem Description:

Given the set of below strings


In above strings only lower case letter "r" is common in all of them.

I know we can use Intersectto find common things in 2 string but how to do using 3 strings?

This code below i did for 2 strings

var commonString = firstPartOfstring
  .Select(x => x)

But cant find how to do for 3 strings

Solution – 1

Intersect is transitive — that means you can string them together in sequence.

var commonString = firstPartOfstring
                  .Select(x => x).FirstOrDefault().ToString();

(nb – you can sequence them in any order – the other attribute of transitive)

Solution – 2

In general case you can query the strings (lines) with a help of Linq Aggregate. Please, note, that to get string from enumeration (IEnumerable<char>) we should use Concat(), not ToString():

using System.Linq;


// Organize the strings into a collection, say, an array 
// (Set, List etc. will do as well)
string[] lines = {


// Query the collection above with a help of Linq:
//   We turn each string into enumeration (IEnumerable<char>)
//   Aggregate all enumerations into one with a help of Intersect
//   Concat characters of the final enumeration to the string
string commonString = string.Concat(lines
  .Select(line => line.AsEnumerable()) // we deal with IEnumerable<char>, not string
  .Aggregate((s, a) => s.Intersect(a))
  .OrderBy(c => c) // In case you want common characters being ordered

if null can appear among the strings, change .Select(...) into

.Select(line => line?.AsEnumerable() ?? Array.Empty<char>())

Please, fiddle youself.

If you want just to intersect three strings you can do it as follow:

string first = "vJrwpWtwJgWrhcsFMMfFFhFp";
string second = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL";
string third = "PmmdzqPrVvPwwTWBwg";

string commonString = string.Concat(first
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.