Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# check if 2 string includes the same chars

Tags:

string

c#

compare

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

like image 500
nirh1989 Avatar asked Apr 30 '26 22:04

nirh1989


1 Answers

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();
like image 195
Tim Schmelter Avatar answered May 03 '26 11:05

Tim Schmelter