检查包含子字符串列表的字符串

问题描述:

如何检查特定字符串以查看它是否包含一系列子字符串? 具体而言是这样的:检查包含子字符串列表的字符串

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 –

决定不检查字符串来限制我的数据返回,而不是限制了我的回归。取一(15 ),如果返回计数超过65,536,则返回空值

可以使用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:真 */

如果性能是一个问题,您可能需要考虑使用RegexStringValidator class

这是一个有趣的问题。正如@Jon所提到的,正则表达式可能是一个好的开始,因为它可以让您一次评估多个负面匹配(可能)。相比之下,幼稚的循环效率会低得多。

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

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); 
} 
}