您可以从命名空间System.Linq的使用扩展方法.Contains()
:
if (abc.ToLower().Contains('s')) { }
没有,检查一个布尔表达式为true,则不需要== true
由于Contains
方法是一种扩展方法,我的解决方案似乎让一些人感到困惑。以下是不需要你两个版本添加using System.Linq;
:
if (abc.ToLower().IndexOf('s') != -1) { }
// or:
if (abc.IndexOf("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }
更新
如果你愿意,你可以写自己的扩展方法,方便重用:
public static class MyStringExtensions
{
public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
{
return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
}
public static bool ContainsAnyCase(this string haystack, char needle)
{
return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
}
}
然后你可以这样称呼它:
if (def.ContainsAnyCaseInvariant('s')) { }
// or
if (def.ContainsAnyCase('s')) { }
在大多数情况下,当处理用户数据时,您实际上想要使用CurrentCultureIgnoreCase
(或ContainsAnyCase
扩展方法),因为这样您可以让系统处理取决于语言的大小写问题。在处理计算问题时,如HTML标签名称等,您需要使用不变文化。
例如:在土耳其,在小写大写字母I
是ı
(无点),而不是i
(以点)。
嗯,我不觉得String.Contains的过载,需要一个char参数。 – 2013-03-13 21:19:02
@ScottSmith这是在[System.Linq](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains.aspx)中定义的扩展方法。你需要添加'使用System.Linq;' – pauloya 2013-08-29 15:29:08
我更喜欢使用'str.IndexOf('s')> = 0',但它可能只是一种风格上的差异。阅读理解时,对我来说更有意义。 – CSS 2016-02-10 19:13:58