NSString的几条小技巧
创建字符串常量字符串
NSString *string = @"i am an iOSDevTip!";常用创建方法
NSString *string = [[NSString alloc] init];string = @"i am an iOSDevTip too!";用initWithString创建字符串
NSString *string = [[NSString alloc] initWithString:@"iOSDevTip is here!"];格式化创建字符串int格式化字符串
int age = 20;NSString *personAge = [NSString stringWithFormat:@"this person age is %d",age];既然int格式化字符串,那么float、double等,也可以格式化字符串。
NSString格式化字符串
NSString *name = @"iOSDevTip";NSString *personName = [NSString stringWithFormat:@"this person name is %@",name];字符串比较isEqualToString方法比较
//比较字符串NSString *stingOne = @"This is an iOSDevTip!";NSString *stringTwo = @"This is an iOSDevTip!";BOOL result = [stingOne isEqualToString:stringTwo];compare方法比较
BOOL result = [stingOne compare:stringTwo] == NSOrderedSame;compare:方法返回值类型为NSComparisonResult。而NSComparisonResult有下面几个枚举值。
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};字符串大小写转换小写转大写
NSString *string = @"This is an iOSDevTip!";[string lowercaseString];大写转小写
NSString *string = @"This is an iOSDevTip!";[string uppercaseString];截取字符串substringToIndex截取字符串
NSString *string = @"This is a operation string!";NSString *subToString = [string substringToIndex:6];截取的subToString为This i
substringFromIndex截取字符串
NSString *subFromString = [string substringFromIndex:6];截取的subFromString为s a operation string!
substringWithRange截取字符串
NSString *rangeString = [string substringWithRange:NSMakeRange(6, 3)];截取的rangeString为s a!
判断字符串是否包含另一个字符串rangeOfString判断
NSString *string1 = @"This is a iOSDevTip";NSString *string2 = @"iOSDevTip";NSRange range = [string1 rangeOfString:string2];NSInteger location = range.location;NSInteger leight = range.length;NSString *logString = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%ld,Leight:%ld",location,leight]];NSLog(@"logString:%@",logString);打印出来:
iOSStrongDemo[8837:2221170] logString:Location:10,Leight:9如果Leight为0,说明不包含。还有更多关于NSString的用法,大家一起探索吧。 |
|