IOS compare 字符串比較
NSString 比較字符串航厚,我介紹一些常用的方法:(轉(zhuǎn)載的??)
NSString *value = @"1234567890";
比較的方法:
[value compare:(NSString *)];
[value compare:(NSString *) options:(NSStringCompareOptions)];
[value compare:(NSString *) options:(NSStringCompareOptions) range:(NSRange)];
傳入的參數(shù):
compare:(NSString *)
傳入一個(gè)需要比較的字符串。
例如 [value compare:@"1234567890"]锰蓬,返回 NSOrderedSame幔睬。
options:(NSStringCompareOptions)
傳入 NSStringCompareOptions 枚舉的值
enum{
NSCaseInsensitiveSearch = 1,//不區(qū)分大小寫比較
NSLiteralSearch = 2,//區(qū)分大小寫比較
NSBackwardsSearch = 4,//從字符串末尾開始搜索
NSAnchoredSearch = 8,//搜索限制范圍的字符串
NSNumbericSearch = 64//按照字符串里的數(shù)字為依據(jù),算出順序芹扭。例如 Foo2.txt < Foo7.txt < Foo25.txt
//以下定義高于 mac os 10.5 或者高于 iphone 2.0 可用
,
NSDiacriticInsensitiveSearch = 128,//忽略 "-" 符號的比較
NSWidthInsensitiveSearch = 256,//忽略字符串的長度麻顶,比較出結(jié)果
NSForcedOrderingSearch = 512//忽略不區(qū)分大小寫比較的選項(xiàng),并強(qiáng)制返回 NSOrderedAscending 或者 NSOrderedDescending
//以下定義高于 iphone 3.2 可用
,
NSRegularExpressionSearch = 1024//只能應(yīng)用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法舱卡。使用通用兼容的比較方法澈蚌,如果設(shè)置此項(xiàng),可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
}
range:(NSRange)
比較字符串的范圍
結(jié)構(gòu)變量:
location: 需要比較的字串起始位置(以0為起始)
length: 需要比較的字串長度
返回值:
typedef enum _NSComparisonResult {
NSOrderedAscending = -1, // < 升序
NSOrderedSame, // = 等于
NSOrderedDescending // > 降序
} NSComparisonResult;
例子:版本號比較
NSString *num1 = @"5.2.0";
NSString *num2 = @"5.3.0";
if ([num1 compare:num2 options:NSNumericSearch] == NSOrderedDescending)
{
ULog(@"%@ is bigger",num1);
}else
{
ULog(@"%@ is bigger",num2);
}
解釋:
NSOrderedDescending是降序灼狰,如果numb1>numb2用這個(gè)函數(shù)相比較那么就等于降序
應(yīng)用實(shí)例
// 獲取當(dāng)前版本號
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
if ([appVersion compare:serverVersion options:NSNumericSearch] == NSOrderedAscending) {
UIAlertView *alert;
alert = [[UIAlertView alloc] initWithTitle:@"有新版本,是否升級!"
message:message
delegate: self
cancelButtonTitle:@"取消"
otherButtonTitles: @"升級", nil];
alert.tag = 20;
[alert show];
}else{
NSLog(@"沒有新版本");
}
//上一次本地存儲的版本號
NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"Version"];
// 獲取當(dāng)前版本號
NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (lastVersion == nil || [currentVersion compare:lastVersion options:NSNumericSearch] == NSOrderedDescending){
NSArray *imageArray = @[@"guidePage_1.png",@"guidePage_2.png",@"guidePage_3.png"];
GuidePageView * guidePageView = [[GuidePageView alloc]initWithFrame:self.window.bounds imageArray:imageArray];
[tabBar.view addSubview: guidePageView];
//第一次進(jìn)入完成后 記錄一下
[[NSUserDefaults standardUserDefaults]setObject:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] forKey:@"Version"];
}