不区分大小写的'Contains(string)'
技术问答
390 人阅读
|
0 人回复
|
2023-09-11
|
有没有办法让下面的回归成真?" R% R6 }7 a; d
string title = "ASTRINGTOTEST";title.Contains("string");
8 w5 L5 |: O+ ]5 N 似乎没有允许我设置过载来区分大小写。目前我把它们都写了,但是很愚蠢(我指的是上下大小写带来的i18n问题)。
. |0 W: t4 }/ P5 P. j; K% v( ] . h% O. F- U7 o- K
解决方案:
8 i4 _- E [" Y$ j8 ^ 您可以使用String.IndexOfMethod并StringComparison.OrdinalIgnoreCase作为搜索类型的传输:6 f& e0 |7 d, z/ J& b
string title = "STRING";bool contains = title.IndexOf("string",StringComparison.OrdinalIgnoreCase) >= 0;& L6 T: T4 }$ H# p
更好地为字符串定义一种新的扩展方法:
" o3 k! d' \# ^' h- y3 k) H2 a+ h. w1 |" k5 e- X
- public static class StringExtensions{ public static bool Contains(this string source,string toCheck,StringComparison comp) return source?.IndexOf(toCheck,comp) >= code]请注意,自 C# 6.0 (VS 2015年 可使用空传播 .,使用旧版本[code]if (source == null) return false;return source.IndexOf(toCheck,comp) >= 0;6 q6 Y' v9 N5 P$ g* j! T+ i
用法:8 L8 V6 e3 X; H2 ?
string title = "STRING";bool contains = title.Contains("string",StringComparison.OrdinalIgnoreCase);: c0 L* u, ~ P/ G' A! i" z( i
|
|
|
|
|
|