2012-07-12 73 views
0

有沒有辦法在C#中執行以下操作,但我正在查找和.indexOf沒有粘貼給我。它是否存在,或者我應該使用什麼其他方法?如何在C#中搜索匹配的字符串數組,如我的代碼

string t = "joke"; 
string sentence = "there is no joke here"; 
string[] array = sentence.Split(" ".ToCharArray()); 

//here is the kicker 
int count = array.indexOf(t); 
return count; 

這應該返回3?

+0

你想要它3,因爲笑話是第4個字? – Maess 2012-07-12 19:36:43

+0

是的,這是正確的。 – Fallenreaper 2012-07-12 19:41:12

回答

0

這會給元素的索引...

int keyIndex = array.ToList().FindIndex(w => w=="joke"); 
+0

爲什麼要將它轉換爲列表? – scottheckel 2012-07-12 19:59:45

+0

@Hexxagonal - 我不知道直接的方法,所以我foudn這種alternet的方式...........沒有其他在它 – 2012-07-12 20:01:58

+0

atlatt給予-1的資源??? – 2012-07-14 05:02:05

1

Array.IndexOf是靜態方法,所以你應該使用這樣的:

int count = Array.IndexOf(array, t); 
0
int indexOfWord = Array.FindIndex(sentence.Split(' '), w => w == t); 

您不必做0123',因爲Split方法的定義中有params關鍵字。編譯器會自動將Split(' ')轉換爲Split(new char[] {' '});)

0

您近:Array.IndexOf是Array中的靜態方法。所以你會有

int index = Array.IndexOf<string>(words, "no"); 

看到區別?

相關問題