[SOLVED] How to create char array of letters from a string array ? (C#)


For example, I have a string:

"Nice to meet you"

, there are 13 letters when we count repeating letters, but I wanna create a char array of letters from this string without repeating letters, I mean for the string above it should create an array like

{'N', 'i', 'c', 'e', 't', 'o', 'y', 'u', 'm'}

I was looking for answers on google for 2 hours, but I found nothing, there were lots of answers about strings and char arrays, but were not answers for my situation. I thought that I can write code by checking every letter in the array by 2 for cycles but this time I got syntax errors, so I decided to ask.


You can do this:

var foo = "Nice to meet you";
var fooArr = s.ToCharArray();
HashSet<char> set = new();

//or if you want without whitespaces you could refactor this as below
set.UnionWith(fooArr.Where(c => c != ' '));

You could even make an extension method:

public static IEnumerable<char> ToUniqueCharArray(this string source, char? ignoreChar)
     var charArray = source.ToCharArray();
     HashSet<char> set = new();
     set.UnionWith(charArray.Where(c => c != ignoreChar));
     return set;

And then you can use it as:

var foo = "Nice to meet you";
var uniqueChars = foo.ToUniqueCharArray(ignoreChar: ' ');

// if you want to keep the whitespace
var uniqueChars = foo.ToUniqueCharArray(ignoreChar: null);

Answered By – ggeorge

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *