在C#
中匹配案例不敏感的字符串
c#的内置方法对大小写。 要执行不敏感的底带检查,您需要采取不同的方法。 Contains()
方法提供了使用IndexOf()
选项的解决方案:StringComparison.OrdinalIgnoreCase
>
<code class="language-csharp">string title = "STRING"; bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;</code>这明确定义了比较类型。 对于清洁代码,扩展方法提供了一个更直观的解决方案:
<code class="language-csharp">public static class StringExtensions { public static bool ContainsIgnoreCase(this string source, string toCheck) { return source?.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0; } }</code>现在,对案例不敏感的检查很简单:
<code class="language-csharp">string title = "STRING"; bool contains = title.ContainsIgnoreCase("string");</code>这种扩展方法增强了可读性并简化了对案例不敏感的字符串比较,在使用资本化可能会有所不同的文本时,尤其有益。
以上是我如何执行不敏感的字符串包含C#中的检查?的详细内容。更多信息请关注PHP中文网其他相关文章!