回答

收藏

不区分大小写的'Contains(string)'

技术问答 技术问答 121 人阅读 | 0 人回复 | 2023-09-11

有没有办法让下面的回归成真?3 z+ _8 q+ v6 l% O1 n
    string title = "ASTRINGTOTEST";title.Contains("string");* Z4 ~( A. z7 |, G. e) m
似乎没有允许我设置过载来区分大小写。目前我把它们都写了,但是很愚蠢(我指的是上下大小写带来的i18n问题)。
4 Y) T1 o  W! _/ s                                                                & _6 Z2 O; \" @7 u& ^: L0 e, @
    解决方案:                                                                % S. [9 i9 k' h4 l% Z$ c6 e
                                                                您可以使用String.IndexOfMethod并StringComparison.OrdinalIgnoreCase作为搜索类型的传输:* H, q! o# W0 y5 c. |5 O
    string title = "STRING";bool contains = title.IndexOf("string",StringComparison.OrdinalIgnoreCase) >= 0;
    2 W/ }7 x1 _  h2 ^& f; h; g2 B
更好地为字符串定义一种新的扩展方法:+ I; C$ O. C/ o8 {  t
    9 w) v- ~5 \  |& b/ k7 Y6 K4 }
  • 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;/ J2 T' D- ]0 V3 T, k/ i( A0 a
用法:  p) f+ i; l8 O6 S
    string title = "STRING";bool contains = title.Contains("string",StringComparison.OrdinalIgnoreCase);
    3 S  Q, S& z8 ^  c8 a
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则