2013-11-03 159 views

回答

0

爲什麼不直接使用.Contains()方法....

string s = "i am a string!"; 
bool matched = s.Contains("am"); 
+0

謝謝你的工作很好:D – user2947576

+0

沒問題。一定要'upvote' *和*'accept'回答!快樂的編碼! :) –

0
String [] words={"word1","word2","word3"}; 
String key="word2"; 
for(int i=0;i<words.Length;i++) 
{ 
if(words[i].Contains(key)) 
Console.WriteLine(words[i]); 
} 
0

您可以使用String.Contains方法等;

string s = "helloHellohi"; 
string[] array = new string[] { "hello", "Hello", "hi", "Hi", "hey", "Hey", "Hay", "hey" }; 

foreach (var item in array) 
{ 
    if(s.Contains(item)) 
    Console.WriteLine(item); 
} 

輸出將是;

hello 
Hello 
hi 

這裏一個demonstration

3

雖然這是一個非常棘手的問題,我會違揹我的直覺並回答它。

構建要搜索List<string>

private List<string> _words = new List<string> { "abc", "def", "ghi" }; 

然後建立一個可愛的小擴展方法是這樣的:

public static bool ContainsWords(this string s) 
{ 
    return _words.Any(w => s.Contains(w)); 
} 

所以現在你可以說:

myString.ContainsWords(); 

整個擴展類可能如下所示:

public static class Extensions 
{ 
    private List<string> _words = new List<string> { "abc", "def", "ghi" }; 

    public static bool ContainsWords(this string s) 
    { 
     return _words.Any(w => s.Contains(w)); 
    } 

    public static bool ContainsWords(this string s, List<string> words) 
    { 
     return words.Any(w => s.Contains(w)); 
    } 
} 

注意:根據您的應用程序的需要,第二種方法是更通用的。它不會從擴展類中獲取列表,而是允許它被注入。但是,這可能是因爲您的應用程序非常特殊,以至於第一種方法更合適。

+1

通過列表ContainsWords將更通用... – Steve

+0

@Steve,是的,它會,這將是一個合理的補充。讓我補充一點。 –

+2

哦,至少從這個問題中可以看出一些有用的東西 – Steve

相關問題