iOS字符串比较

作者: 莽原奔马668 | 来源:发表于2017-04-21 15:08 被阅读3032次

    在开发的过程中,经常遇到需要比较两个字符串,当然比较的方法很多,下面总结一下比较字符串的方法

    一.用C语言比较:strcmp函数
    char string1[] = "string!";
    char string2[] = "string!";
    if(strcmp(string1, string2) == 0)
    {
        NSLog(@"1");
    }
    

    C中一般都是操作单个字符,不像OC有字符串对象的概念,C中需要操作一串字符,就需要用到数组.

    二.用OC语言比较

    1.isEqualToString方法:判断字符串是否相等

    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 isEqualToString:astring02];
    NSLog(@"result:%d",result);
    

    2.compare方法(comparer返回的三种值)

    • NSOrderedSame 判断两者内容是否相同
    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"This is a String!";    
    BOOL result = [astring01 compare:astring02] == NSOrderedSame;    
    NSLog(@"result:%d",result);    
    
    • NSOrderedAscending 判断两对象值的大小(按字母顺序进行比较,astring02大于astring01为真)
    NSString *astring01 = @"This is a String!";
    NSString *astring02 = @"this is a String!";
    BOOL result = [astring01 compare:astring02] == NSOrderedAscending;    
    NSLog(@"result:%d",result);
    
    • NSOrderedDescending 判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真)
    NSString *astring01 = @"this is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 compare:astring02] == NSOrderedDescending;    
    NSLog(@"result:%d",result);
    

    3.不考虑大小写比较字符串

    • NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真
    NSString *astring01 = @"this is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 caseInsensitiveCompare:astring02] == NSOrderedSame;    
    NSLog(@"result:%d",result);     
    
    • NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch:进行完全比较,区分大小写 NSNumericSearch:比较字符串的字符个数,而不是字符值。
    NSString *astring01 = @"this is a String!";
    NSString *astring02 = @"This is a String!";
    BOOL result = [astring01 compare:astring02
                                options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame;    
    NSLog(@"result:%d",result);
    

    相关文章

      网友评论

      • JJJJJJC:您好我想问一下,如果我用 > 来比较两个字符串是怎么比较的?
        比如
        str1 = @“32”,str2 = @“2”
        if (str1>str2) {
        NSLog(@"str1 > str2");
        }else if (str1<str2){
        NSLog(@"str1 < str2");
        }
        我打log发现 输出的是(str1 < str2)
        莽原奔马668:OC语言不支持用“>”比较字符串,如果像你这样字符串都是由数字组成的,可以转化成整型再比较
        str1.integerValue > str2.integerValue

      本文标题:iOS字符串比较

      本文链接:https://www.haomeiwen.com/subject/ciudzttx.html