2

I habe a sentence:

    string x = "This is a first string, this is a second string.";

When add every word into an array

    string[] words = x.Trim().Split(new char[] { ' ' });

What do I have to do to add only unique words into the array ?

4 Answers 4

7

Use Linq.

Also, since Split takes a params array, you don't need the new char[] part.

string[] words = x.Trim().Split(' ').Distinct().ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

An answer with three upvotes in a full minute and SO decides not to tell me at all. Geez.
You might also want to use a regex or something similar to strip out any punctuation, so that you don't have one entry for "string," and one entry for "string.".
haha, you were faster ;) It's like: "Ladies and Gentlemen, start your engines!"
You'll also want to handle different casing of a word
1

Use

string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();

Comments

0

You have to do is:

string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();

Comments

0

Before adding the string to array, you could traverse the array to see if word already exists.

For example:

List<string> arrayStr = new List<string>();

Before adding, you could do

if(arrayStr.Contains(abc))
MessageBox.Show("Word already exists");
else
arrayStr.Add(abc);

hope this helps

Comments

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.