C#比较字符串ignoreCase

时间:2013-05-09 21:39:48

标签: c# string compare ignore-case

在这个测试方法中,我需要比较user3的字符串,同时忽略区分大小写。我想我应该使用CultureInfo.InvariantCulture来忽略Case。这是实现这一目标的最佳方式,还是有更好的方法?

            //set test to get user 
            AsaMembershipProvider prov = this.GetMembershipProvider();        

            //call get users
            MembershipUser user1 = prov.GetUser("test.user", false);
            //ask for the username with deliberate case differences
            MembershipUser user2 = prov.GetUser("TeSt.UsEr", false);
            //getting a user with Upper and lower case in the username.
            MembershipUser user3 = prov.GetUser("Test.User", false);

            //prove that you still get the user, 
            Assert.AreNotEqual(null, user1);
            Assert.AreNotEqual(null, user2);

            //test by using the “.ToLower()” function on the resulting string.
            Assert.AreEqual(user1.UserName.ToLower(), user2.UserName.ToLower());
            Assert.AreEqual(user1.UserName, "test.user");
            Assert.AreEqual(user3.UserName, "test.user");

3 个答案:

答案 0 :(得分:5)

Assert.AreEqual与ignoreCase参数一起使用是更好的,因为它不需要创建新字符串(并且,正如@dtb所指出的,您可以按照特定文化的规则工作信息)

Assert.AreEqual(user1.UserName, user2.UserName, true, CultureInfo.CurrentCulture);

答案 1 :(得分:3)

StringInstance.ToUpperInvariant()

user1.UserName.ToUpperInvariant() == user3.UserName.ToUpperInvariant();

user3.UserName.ToUpperInvariant() == "TEST.USER";  

答案 2 :(得分:1)

以简单的形式;你可以比较两个字符串而忽略它们的情况,如下所示。

Assert.AreEqual(0,string.Compare("test", "TEST", true));

我不确定;为什么你需要采取非文化特定案例的路线,因为案例是一个简单的(非本地化)单元测试案例。话虽如此,如果您还想继续这个方向,请参考this链接。