2016-07-25 102 views
1

基本上我要檢測一個以上的字符串,當前的代碼示例是C#多個字符串包含

if (!str3.Contains("example1")) 
{ 
    continue; 
} 

我怎麼會加上「例1」,「例題」 &「示例3」

+1

與通常測試多個條件相同的方式 - 用'&&'或'||'將它們連接在一起。例如:'if(!str3.Contains(「example1」)&&!str3.Contains(「example2」)...)' –

+0

檢測它們全部或任何一個? –

+0

如果你有很多它們,你可以創建一個'IEnumerable ',比如'List ',並用適當的邏輯循環遍歷你的外部循環。 –

回答

5

您可以使用Linq如果你想與一個大名單,以測試:

var excludes = new[] { "example1", "example2", "example3" }; 

//your loop here 
{ 
    if (!excludes.Any(x => str3.Contains(x))) 
    { 
     continue; 
    } 
} 
0

就個人而言,我更喜歡循環,因爲它解決了手動擴大你的代碼問題的方式。例如...

public void MyMethod(string param) 
{ 
    var myList = new string[] 
    { 
     "example1", 
     "example2", 
     "example3" 
    }; 
    foreach (var item in myList) 
    { 
     if (!param.Contains(item)) continue; 
    } 
    //Do something here 
} 

基本上,你正在創建一個你想要搜索的物品的集合。使用它,你循環它們並將它們與目標字符串進行比較。

我不知道該函數的全部範圍,所以我不能完全添加更多,但這已經很基本了。

0

如果字符串遵循特定的模式,正則表達式總是一個乾淨的選項。

如果字符串 「例1」, 「例2」 等等,你可以使用這個表達式:

/example[0-9]+/g 

一些C#發現第一和第二場比賽(來源:http://www.dotnetperls.com/regex):

// Get first match. 
Match match = Regex.Match(str3, @"example[0-9]+"); 
if (match.Success) 
{ 
    //matched one of the strings 
} 

// Get second match. 
match = match.NextMatch(); 
if (match.Success) 
{ 
    //process second match 
}