1

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.

6
  • 2
    We may help you with those syntax errors, if you provide your code Commented Mar 12, 2022 at 10:15
  • 'N' is different from 'n'? Commented Mar 12, 2022 at 10:21
  • use hashset learn.microsoft.com/en-us/dotnet/api/… The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. Commented Mar 12, 2022 at 11:36
  • @HansKesting I am not sure about my code cuz I had no chance to verify this code because of syntax errors, so I thought that maybe my algorithm is not correct and asked for a direct answer Commented Mar 12, 2022 at 11:43
  • If this is homework, then you are maybe not allowed to use the Linq-based answers Commented Mar 13, 2022 at 11:10

6 Answers 6

4

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 != ' '));

UPDATE: 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);
Sign up to request clarification or add additional context in comments.

Comments

2

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));

I have added ToLower() if you dont do differences between uppercase and lowercase, if case is sensitive you just put off this extension.. HashSet suppresses all duplicates letters

test: Fiddle

Comments

2

I tried this one and it works too

"Nice to meet you".Replace(" ", "").ToCharArray().Distinct();

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
You don't really need ToCharArray - a string is already an IEnumerable<char>. But you may need an additional .ToArray() at the end, to make the result an array
2

A very short solution is to use .Except() on the input string:

string text = "Nice to meet you";

char[] letters = text.Except(" ").ToArray();

Here, .Except():

  1. translates both the text string and the parameter string (" ") to char collections
  2. filters out all the chars in the text char collection that are present in the parameter char collection
  3. returns a collection of distinct chars from the filtered text char collection

Example fiddle here.


Visualizing the process

Let's use the blue banana as an example.

var input = "blue banana";
  1. input.Except(" ") will be translated to:
{ 'b', 'l', 'u', 'e', ' ', 'b', 'a', 'n', 'a', 'n', 'a' }.Except({ ' ' })
  1. Filtering out all ' ' occurrences in the text char array produces:
{ 'b', 'l', 'u', 'e', 'b', 'a', 'n', 'a', 'n', 'a' }
  1. The distinct char collection will have all the duplicates of 'b', 'a' and 'n' removed, resulting in:
{ 'b', 'l', 'u', 'e', 'a', 'n' }

1 Comment

I like this answer; the interesting (and at first sight not so obvious) thing here is that Except is a set operation which ensures that duplicates are removed.
1

A solution just using for-loops (no generics or Linq), with comments explaining things:

// get rid of the spaces
String str = "Nice to meet you".Replace(" ", "");

// a temporary array more than long enough (we will trim it later)
char[] temp = new char[str.Length];

// the index where to insert the next char into "temp". This is also the length of the filled-in part
var idx = 0;

// loop through the source string
for (int i=0; i<str.Length; i++)
{
    // get the character at this position (NB "surrogate pairs" will fail here)
    var c = str[i];
    
    // did we find it in the following loop?
    var found = false;

    // loop through the collected characters to see if we already have it
    for (int j=0; j<idx; j++)
    {
        if (temp[j] == c)
        {
            // yes, we already have it!
            found = true;
            break;
        }
    }
    
    if (!found)
    {
        // we didn't already have it, so add
        temp[idx] = c;
        idx+=1;
    }
}

// "temp" is too long, so create a new array of the correct size
var letters = new char[idx];
Array.Copy(temp, letters, idx);
// now "letters" contains the unique letters

That "surrogate pairs" remark basically means that emojis will fail.

Comments

0
String str  = "Nice To meet you";
char[] letters = str.ToLower().Except(" ").ToArray();

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
See the answer by Astrid E to see why "Except" works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.