iOS NSString 常用的語法

1.字串比較
NSString *string1 = [[NSString alloc]initWithString:@"I am String1"];
NSString *string2 = [[NSString alloc]initWithString:@"I am String2"];
NSLog(@"%@ 與 %@ 是否相同: %@", string1, string2, [string1 isEqualToString:string2] ? @"是":@"否");
[string1 release];
[string2 release];


2.字串比較(不區分大小寫)
NSString *string1 = [[NSString alloc]initWithString:@"I am String1"];
NSString *string2 = [[NSString alloc]initWithString:@"i am string1"];
NSLog(@"%@ 與 %@ 是否相同(不考慮大小寫): %@", string1, string2,
[string1 caseInsensitiveCompare:string2]==NSOrderedSame ? @"是":@"否");
[string1 release];
[string2 release];

3.搜尋字串
NSString *string1 = [[NSString alloc]initWithString:@"This is a book"];
//此處NSRange 為區分大小寫
NSRange searchString1 = [string1 rangeOfString:@"book"];
NSRange searchString2 = [string1 rangeOfString:@"pen"];
//不區分大小寫寫法為
NSRange searchString1 = [string1 rangeOfString:string2 options:NSCaseInsensitiveSearch | NSNumericSearch];
NSLog(@"%@ 是否有book字串: %@",string1, searchString1.location == NSNotFound ? @"否" : @"是" );
NSLog(@"%@ 是否有pen 字串: %@",string1, searchString2.location == NSNotFound ? @"否" : @"是" );
[string1 release];

4.取出字串
NSString *string1 = [[NSString alloc]initWithString:@"this is a string"];
NSLog(@"%@ 取出從頭自第三位(不包含第三位)的字串: %@",string1, [string1 substringToIndex:2]);
NSLog(@"%@ 取出第三位(包含) 後所有字串: %@",string1, [string1 substringFromIndex:2]);
NSLog(@"%@ 取出第三位至第七位的字串: %@",string1, [string1 substringWithRange:NSMakeRange(5,4)]);
[string1 release];

5.替換字串
NSString *string1 = [[NSString alloc]initWithString:@"this is a book"];
NSString *string2 = [[NSString alloc]initWithString:@"pen"];
NSLog(@"%@ 替換後 %@",string1,
[string1 stringByReplacingOccurrencesOfString:@"book" withString:@"pen"]);
[string1 release];
[string2 release];

6.字串轉成array
NSString *string1 = [[NSString alloc]initWithString:@"apple,book,cat,dog,egg"];
NSLog(@"%@",[string1 componentsSeparatedByString:@","]);
[string1 release];

7.array轉成字串
NSArray *array = [[NSArray alloc]initWithObjects:@"apple",@"book",@"cat",@"egg",nil];
NSLog(@"%@",[array componentsJoinedByString:@","]);
[array release];

留言

熱門文章