1

I have a string and I don't know its count of items. I want to split this string array into a new array. After that I need to remove duplicate items as in the example below.

For example in the below: the word "hi" and "friends" goes twice, but we write them once in second array, it doesn't always have to be two over, sometimes 3 or more over and word "hi" and "friends" only for example, maybe other words goes two or more times).

For example;

string[] myString = {"hello friends", "hi guys", "hi friends", "how are", "123654 u?", "today man", "! ?", "maybe tomorrow", "5 2-", "99 1585126", "(/&&/& _____"};

I want to split it into a new string array like that (according space characater);

string[] new = {"hello", "friends", "hi", "guys", "how", "are", "123654", "u?", "today", "man", "!", "?", "maybe", "tomorrow","5" ,"2-" ,"99", "1585126", "/&&/&", "_____"} ;
0

3 Answers 3

7

Use SelectMany and Distinct:

string[] newArray = myString.SelectMany(s => s.Split(' ')).Distinct().ToArray();

If you want to compare in a case insensitive manner pass the appropriate comparer to Distinct:

string[] newArray = myString.SelectMany(s => s.Split(' ')).Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray();
Sign up to request clarification or add additional context in comments.

5 Comments

Might be better to use Split(null) to separate by any white-space instead of just one space...
@Johnny: Then use Split() without an argument. But in what way better? OP hasn't mentioned that he wants to include all white-space- or new-line-characters
@Rango in the way the code is more robust. I agree in this specific example it doesn't matter but generally...
@Johnny: not necessarily more robust, that depends on the business rules of OP which i don't know. If he says he wants to split by spaces("according space character") i don't provide a solution that silently splits also by other characters.
@Rango I forgot. I mark it right now. Thank you again.
1

You can write a function:

public string[] GetDistinctArray(string[] input) { var str = string.Join("",input).Split(' ');return str.Distinct().ToArray();}

Comments

0

Use "SelectMany" and "Distinct" with "Trim" :

var arr = myString.SelectMany(x => x.Trim().Split(' ')).Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray();

5 Comments

Why with trim? What's the difference from the top answer?
Do you want empty string in your result?
Like what for example?
Example input : string[] myString ={" hello "}; unless "Trim()" result -> {"", "hello"}
Hmm. Thank you for answer.

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.