Check if a word contains a character not in the alphabet array

Viewed 193

I have this alphabet array and a word:

string Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Array alphabet = Digits.ToCharArray();
string target = "ABC?0";

I want to check if target contains a character which is not available in the alphabet array and if so, print the character. So in the above example, there are two characters available in target and not available in alphabet ("0" and "?"). How can I do that ?

2 Answers

You don't need ToCharArray. Simply just use the Except method like this:

var result = target.Except(Digits).ToArray();

And if you still need to use alphabet, change it's type to char[]:

char[] alphabet = Digits.ToCharArray();
var result = target.Except(alphabet).ToArray();

And if you would like to see the result as string, you can use string.Join like this:

var result = string.Join("", target.Except(Digits));

Just make sure that using System.Linq; has been already added to your using statements.

Related