nirh1989
nirh1989

Reputation: 209

c# check if 2 string includes the same chars

I created 3 strings:

string a = "abcdgfg";
string b = "agbfcd";
string c = "axcvn";

I want to create the following check but i can't find out how: Need to check if in string a and string b there are the same latters (never mind the order or if a latter shown more than once, just need to check if the same latter appears on both strings). Then i need to do the same check for string a and string c.

as you can see: string a and string b have the same latters, stringa a and string c don't.

after i do the checking i simply print a massage if the strings have the same latter or not

Can anyone show me how to do the cheking?

Edit:

after check "a" and "c", it o should print the first latter that came up and not match between "a" and "c"

Thanks

Upvotes: 2

Views: 6343

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460108

I would suggest to use a HashSet<T> and it's SetEquals:

var aSet = new HashSet<char>(a);
var bSet = new HashSet<char>(b);
bool abSame = aSet.SetEquals(b);

Edit

after check "a" and "c", it o should print the first latter that came up and not match between "a" and "c"

Then you can use HashSet.SymmetricExceptWith:

if (!abSame)
{
    aSet.SymmetricExceptWith(bSet);
    Console.WriteLine("First letter that is either in a and not in b or in b and not in a: " + aSet.First()); 
}

By the way, this can also replace the SetEquals check:

aSet.SymmetricExceptWith(bSet); // removes all characters which are in both
if (aSet.Any())                 // missing charaters in one of both strings
{
    Console.WriteLine("First letter that is either in a and not in b or in b and not in a: " + aSet.First()); 
}

The original answer using Except + Any had a subtle bug. Checking the length is not sufficient if there are duplicates. So you need to check from both directions or use Distinct first. Both approaches are inefficient compared to the HashSet.SetEquals-method which is a O(n) operation.

bool abSame = !a.Except(b).Any() && !b.Except(a).Any();

Upvotes: 4

Dejan Dular
Dejan Dular

Reputation: 373

private bool HaveSameLetters(string a, string b)
{       
     return a.All(x => b.Contains(x)) && b.All(x => a.Contains(x));
}

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Need to check if in string a and string b there are the same latters (never mind the order or if a latter shown more than once, just need to check if the same latter appears on both strings).

You can do it like this:

bool same = a.Distinct().OrderBy(c => c)
           .SequenceEqual(b.Distinct().OrderBy(c => c));

This simply sorts the characters of two strings and checks if the two ordered sequence are equal. You can use the same method for a and c.

Upvotes: 3

Related Questions