Viral Viral - 4 months ago 38
C# Question

String To Verify

I am a developer.
I wanted to check if a source string contained all of the characters in the destination string.

Source String : Test Check
Destination sting : Check Test

Then wanted to check if each char(T,e,s,t,c,h,e,c,k) are present in the destination string?
The source string can contain numeric/alphanumeric/special characters to compare with destination string.

We can verify by loop through each & every character from the destination and match that to destination but that would takes time.

Is there any simple way to check this?


You can use Except + Any:

string sourceString ="Test Check";
string destString ="Check Test";
bool destStringContainsSource = !sourceString.Except(destString).Any();

or with HashSet.SetEquals:

HashSet<char> set = new HashSet<char>(sourceString);
destStringContainsSource = set.SetEquals(destString);

Both approaches don't take the number of characters into account.

The Except-approach does not even check if the destination-string contains more characters. It's just checking if the second string is a subset of the first. SetEquals is not quite the same.

You can use HashSet.IsSubsetOf to get the same behaviour:

HashSet<char> set = new HashSet<char>(sourceString);
bool sourceIsSubsetOfDest = set.IsSubsetOf(destString);

I would prefer the HashSet approaches since they are very efficient and most of all clear.