Home > OS >  How to create char array of letters from a string array ? (C#)
How to create char array of letters from a string array ? (C#)

Time:03-12

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.

CodePudding user response:

You can do this:

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

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

CodePudding user response:

this piece of code does the job:

var sentence = "Nice To meet you";
var arr = sentence.ToLower().Where(x => x !=' ' ).ToHashSet();
Console.WriteLine(string.Join(",", arr));

HashSet suppresses all duplicates letters

test: Fiddle

  • Related