我在C#又名这里给一个字符串变量,我想过滤这样,并将它返回true或false:如何使用c#使用SQL中的LIKE逻辑来过滤字符串?
product_name LIKE '%BONUS NAME%'
我怎么能这样做吗?
PS:我必须这样做,在C#不是SQL
我在C#又名这里给一个字符串变量,我想过滤这样,并将它返回true或false:如何使用c#使用SQL中的LIKE逻辑来过滤字符串?
product_name LIKE '%BONUS NAME%'
我怎么能这样做吗?
PS:我必须这样做,在C#不是SQL
if(product_name.Contains("BONUS NAME"))
// do stuff..
简单的选择:使用String.Contains
http://msdn.microsoft.com/en-us/library/system.string.contains.aspx
从MSDN页面
// 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);
}
}
/*
This example produces the following results:
Is the string, s2, in the string, s1?: True
*/
例更强大:使用正则表达式库
http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx
正则表达式给你更多的权力,但你可以模仿SQL的通配符正则表达式运算符“”和“*”
string text = "The quick brown fox jumps over the lazy dog";
string pat = @"fox";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
我的优选匹配的字符串的一部分的方法是通过使用该方法IndexOf
:
string input = "This is My FuLl string";
string lookFor = "full";
bool foundIt = input.IndexOf(lookFor, StringComparison.OrdinalIgnoreCase) >= 0;
不同于Contains
这开辟了不区分大小写匹配。