开发者

Add elements into an array when the element doesnt exist

开发者 https://www.devze.com 2023-03-03 01:35 出处:网络
I habe a sentence: string x = \"This is a first string, this is a second string.\"; When add every word into an array

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 ?


Use Linq.

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

string[] words = x.Trim().Split(' ').Distinct().ToArray();


Use

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


You have to do is:

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号