How to test for Case-Insensitive StringA.Contains(StringB)?
如何测试子字符串是否包含在其他字符串中,但不区分大小写?
编辑:它还应该与全球化合作。
使用string.indexof方法(string,stringcomparison)
1 2 3 4 5 6 7 8 9 10 | string str ="Some test String"; string str2 ="test"; if (str.IndexOf(str2, StringComparison.InvariantCultureIgnoreCase) > 0) { //str contains str2 } else { //str does not contain str2 } |
在执行检查之前,可以将两个字符串都转换为大写:
1 | string1.ToUpperInvariant().Contains(string2.ToUpperInvariant()) |
或者,如果在定义案例不连续性时要考虑当前区域性:
1 | string1.ToUpper().Contains(string2.ToUpper()) |
或者甚至可以通过调用接受
代码分析警告CA1308中描述了应该转换为大写而不是小写的原因:将字符串规范化为大写:
Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters.
你可能会想,"一小群角色"会受到什么影响,根据迈克尔·S·卡普兰的说法,显然至少有些格鲁吉亚剧本有这个问题。
你可以使用这个超负荷的
对于
Compare strings using culture-sensitive sort rules, the invariant
culture, and ignoring the case of the strings being compared.
1 2 | string string1 ="YOURSTRING"; bool containsornot = string1 .IndexOf("yourstring", StringComparison.InvariantCultureIgnoreCase) >= 0; |
这是一个
1 | string1.ToUpper().Contains(string2.ToUpper()) |
是否尝试了String1.IndexOf(String2,StringComparison.InvariantCultureIgnoreCase)
或使用StringComparison.OrdinalIgnoreCase
单击此处获取更多信息