James
James

Reputation: 1945

Find common characters from group of string

Given the set of below strings

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg

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
  .Intersect(secondPartOfString)
  .Select(x => x)
  .FirstOrDefault()
  .ToString();

But cant find how to do for 3 strings

Upvotes: 3

Views: 488

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

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 = {
  "vJrwpWtwJgWrhcsFMMfFFhFp",
  "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
  "PmmdzqPrVvPwwTWBwg",
};

...

// 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
  .Intersect(second)
  .Intersect(third));

Upvotes: 2

Hogan
Hogan

Reputation: 70523

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

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

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

Upvotes: 0

Related Questions