我HABE了一句:添加元素到一個數組時,元素犯規存在
string x = "This is a first string, this is a second string.";
當每一個單詞添加到一個數組
string[] words = x.Trim().Split(new char[] { ' ' });
我有什麼做的,只添加唯一字進入數組?
我HABE了一句:添加元素到一個數組時,元素犯規存在
string x = "This is a first string, this is a second string.";
當每一個單詞添加到一個數組
string[] words = x.Trim().Split(new char[] { ' ' });
我有什麼做的,只添加唯一字進入數組?
使用Linq。
另外,由於Split需要一個params數組,所以不需要新的char []部分。
string[] words = x.Trim().Split(' ').Distinct().ToArray();
使用
string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();
你要做的是:
string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();
之前添加字符串數組,你可以遍歷數組,看字已經存在。
例如:
List<string> arrayStr = new List<string>();
加入之前,你可以做
if(arrayStr.Contains(abc))
MessageBox.Show("Word already exists");
else
arrayStr.Add(abc);
希望這有助於
在全分鐘要變三upvotes的答案和SO決定不告訴我在所有。吉茲。 – BoltClock 2011-05-03 13:34:27
您可能還想使用正則表達式或類似的東西來去除任何標點符號,以便您沒有一個「string」條目和一個「string。」條目。 – 2011-05-03 13:35:01
哈哈,你快了;)就像:「女士們,先生們,開啓你的引擎吧!」 – 2011-05-03 13:35:10