我有一个字符串,它可以获取如下所示的任何可能的值(请注意,其中两个值可以与下面的message1,message4相同,但是请记住,它可以使用相同或不同的大小写,但是我想忽略大小写并从列表中进行比较,我得到了这个。)
string Message = "No need of validation";
string Message = "No need of validation for certain members only"
string Message = "Validation for this member - No need of validation"
string Message = "no need of validation";
Message.IndexOf("No need of validation", StringComparison.CurrentCultureIgnoreCase) >= 0)
现在我上面的代码将在2、3种情况下返回true / false?
我希望仅对1,4为true,对2,3为false。请确认一下如果这不正确,请帮我修改代码
答案 0 :(得分:0)
如果按原样运行,则所有4个都是正确的。
string Message = "No need of validation";
Console.WriteLine("1 : {0}", Message.IndexOf("No need of validation", StringComparison.CurrentCultureIgnoreCase));
Message = "No need of validation for certain members only";
Console.WriteLine("2 : {0}", Message.IndexOf("No need of validation", StringComparison.CurrentCultureIgnoreCase));
Message = "Validation for this member - No need of validation";
Console.WriteLine("3 : {0}", Message.IndexOf("No need of validation", StringComparison.CurrentCultureIgnoreCase));
Message = "no need of validation";
Console.WriteLine("4 : {0}", Message.IndexOf("No need of validation", StringComparison.CurrentCultureIgnoreCase));
这是因为忽略大小写的比较字符串在每个消息字符串中都存在,因此索引将始终为0或更高。
如果不管大小写如何都比较字符串是否相等,则应该使用字符串Compare:
Message = "No need of validation";
Console.WriteLine("1 : {0}", string.Compare(Message,"No need of validation", true));
Message = "No need of validation for certain members only";
Console.WriteLine("2 : {0}", string.Compare(Message, "No need of validation", true));
Message = "Validation for this member - No need of validation";
Console.WriteLine("3 : {0}", string.Compare(Message, "No need of validation", true));
Message = "no need of validation";
Console.WriteLine("4 : {0}", string.Compare(Message, "No need of validation", true));
哪个会给您想要的结果。
答案 1 :(得分:0)
如果我正确理解了结果,则可以使用旧的string.Compare
,它自.Net 1.1起就出现了
Compare(String, String, CultureInfo, CompareOptions)
使用指定的规则比较两个指定的String对象,并且 返回一个整数,指示它们在排序中的相对位置 订单。
返回
Int32一个32位带符号整数,指示词法关系 在strA和strB之间,如下表所示
值条件
- 按排序顺序,strA小于零strA之前。
- 按排序顺序,零strA出现在与strB相同的位置。
- 大于strA的strA大于零。
示例
string Message1 = "No need of validation";
string Message2 = "No need of validation for certain members only";
string Message3 = "Validation for this member - No need of validation";
string Message4 = "no need of validation";
Console.WriteLine(string.Compare("No need of validation", Message1, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine(string.Compare("No need of validation", Message2, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine(string.Compare("No need of validation", Message3, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine(string.Compare("No need of validation", Message4, StringComparison.InvariantCultureIgnoreCase));
输出
0
-1
-1
0