中匹配案例不敏感的字符串
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中文網其他相關文章!