iOS中字符串处理之二

2016-08-09  本文已影响338人  HJXu

这篇主要对字符串之间的比较做个简单总结

NSString 两个字符串的比较,用 a compare:b 来比,得出的结果分3种    
1. 26个字母比较  越靠后面越大  
    NSString *a = @"abcabc";  
    NSString *b = @"abcabd";  
    BOOL result = [a compare:b];  
    if (result == NSOrderedSame) {          
// NSOrderedSame = 0 完全一样  
        NSLog(@"a = b");  
    }else if(result == NSOrderedAscending) 
 // NSOrderedAscending = -1  递增
        NSLog(@"a < b");  
    else{                        
 //NSOrderedDescending = +1  递减
        NSLog(@"a > b");  
    }  
2.比较数字或者符号,或者字母 什么都行  
   NSString *a = @"20160809abc";  
    NSString *b = @"20160809abd";  
    BOOL result = [a compare:b];  
    if (result == NSOrderedSame) {      
    // NSOrderedSame = 0 完全一样  
        NSLog(@"a = b");  
    }else if(result == NSOrderedAscending)  
   // NSOrderedAscending = -1  
        NSLog(@"a < b");  
    else{                                   
  //NSOrderedDescending = +1  
        NSLog(@"a > b");  
    }  
3.不考虑大小写比较字符串   
[a caseInsensitiveCompare:b]  
- (void)viewDidLoad  
{  
    NSString *a = @"i love my girlfriend.";  
    NSString *b = @"I Love My Girlfriend.";  
    NSLog(@" \n a:  %@ \n",a);  
    NSLog(@" \n b:  %@ \n",a);  
    BOOL result = [a caseInsensitiveCompare:b] ==  NSOrderedSame;  
}  
   //result = (BOOL) YES;  
  
4.不考虑大小写比较字符串   
[a caseInsensitiveCompare:b]  
- (void)viewDidLoad  
{  
    NSString *a = @"i love my boyfriend.";  
    NSString *b = @"Little baby.";  
    NSLog(@" \n a:  %@ \n",a);  
    NSLog(@" \n b:  %@ \n",a);  
    BOOL result = [a caseInsensitiveCompare:b] ==  NSOrderedAscending;  
}  
//result = (BOOL) YES;  
  
5. 有选择的比较大小   [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch]  
- (void)viewDidLoad  
{  
    NSString *a = @"i love my boyfriend.";  
    NSString *b = @"I Love My Boyfriend.";  
    NSLog(@" \n a:  %@ \n",a);  
    NSLog(@" \n b:  %@ \n",b);  
    BOOL result = [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch] ==  NSOrderedSame;  
}  
//result = (BOOL)YES;  
NSCaseInsensitiveSearch  忽略大小写的比较字符串  
NSNumericSearch       比较字符串的个数  
NSLiteralSearch       区分大小写,进行完全比较 
上一篇下一篇

猜你喜欢

热点阅读