2011-11-29 142 views
0

如何檢查特定字符串以查看它是否包含一系列子字符串? 具體而言是這樣的:檢查包含子字符串列表的字符串

public GetByValue(string testString) { 

    // if testString contains these substrings I want to throw back that string was invalid 
    // string cannot contain "the " or any part of the words "College" or "University" 

    ... 
} 
+0

取決於您將來如何看待這種變化。正則表達式可能是一個好的開始。你有嘗試過什麼嗎? – Jon

+0

不知道從哪裏開始......我的數據訪問層使用輸入的字符串進行搜索......如果字符串包含「the」或「college」或「university」這些單詞的任何部分 - 例如:「 col「或」uni「 - 那麼返回的行太多,太泛化。就增長而言,我只關心這三個詞。我在DAL中使用Linq to SQL –

回答

0

決定不檢查字符串來限制我的數據返回,而不是限制了我的迴歸。取一(15 ),如果返回計數超過65,536,則返回空值

0

可以使用string.Contains()方法

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

// This example demonstrates the String.Contains() method 
using System; 

class Sample 
{ 
public static void Main() 
{ 
string s1 = "The quick brown fox jumps over the lazy dog"; 
string s2 = "fox"; 
bool b; 
b = s1.Contains(s2); 
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b); 
} 

} /* 該示例產生以下結果:

字符串s1是否爲字符串s2:真 */

0

這是一個有趣的問題。正如@Jon所提到的,正則表達式可能是一個好的開始,因爲它可以讓您一次評估多個負面匹配(可能)。相比之下,幼稚的循環效率會低得多。

0

您可以檢查它遵循....

class Program 
{ 



public static bool checkstr(string str1,string str2) 
{ 
bool c1=str1.Contains(str2); 
return c1; 

}

public static void Main() 
{ 
string st = "I am a boy"; 
string st1 = "boy"; 

bool c1=checkstr(st,st1); 
//if st1 is in st then it print true otherwise false 
     System.Console.WriteLine(c1); 
} 
} 
相關問題