iOS 字符串NSString 的一些常用方法
一、字符串创建
1、 NSString *str1 = [NSString new];
2、 NSString *str2 = @"字符串内容";
二、字符串拼接
1、 NSString *str3 = [NSString stringWithFormat:@"%@",str2];
2、字符串比较:isEqualToString 比较两个字符串内容是不是相等;
三、字符串的比较
- (NSComparisonResult)compare:(NSString *)string; //区分大小写比较
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; //附带条件比较
比较返回的枚举有3个值:NSOrderedAscending (小于),NSOrderedSame (相等),NSOrderedDescending (大于)
1 NSString *str1 = @"Goods"; 2 NSString *str2 = @"Hello"; 3 if ([str1 commonPrefixWithString:str2 options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame) 4 { 5 NSLog(@"不区分大小写比较相同"); 6 //多个比较条件 中间用"|"分开 7 } 8 9 // - (BOOL)hasPrefix:(NSString *)aString; 判断字符串是否以开头 10 // - (BOOL)hasSuffix:(NSString *)aString; 判断字符串是否以结尾 11 // - (NSRange)rangeOfString:(NSString *)aString; //字符串中查找字符 12 // NSString *uppercaseString; 将字符串全改为大写 13 // NSString *lowercaseString; 将字符串全改为小写 14 // NSString *capitalizedString;只将字符串首字母改为大写 15 // NSArray *arr = [str1 componentsSeparatedByString:@","] //字符串 以逗号分隔成数组
1 // 字符串长度获取:length 2 NSString *str1 = @"abc"; 3 NSString *str2 = @"abe"; 4 unsigned long len =(int)[str1 length]; 5 NSLog(@"str1的长度为:%lu",len); //len =3; 6 7 // 字符串比较:isEqualToString比较两个字符串的内容是否相同; 8 BOOL isE = [str2 isEqualToString: str1]; 9 NSLog(@"%d",isE); //比较内容是否相等则为1,地址也相等,不相等为0; 10 11 // compare:比较两个字符串的大小 12 int ste = [str1 compare:str2]; 13 NSLog(@"%d",ste);//比较AssIc码值,相等为O,str1<str2= -1;否则为1; 14 15 // 字符串开头:hasPrefix //字符串结尾:hasSuffix 16 BOOL isf = [str2 hasPrefix:@"ab"]; 17 BOOL ise = [str2 hasSuffix:@"be"]; 18 NSLog(@"字符串开头%d,字符串结尾:%i",isf,ise);//判断字符串开头是否有 “ab”; 19 20 // 插入:insertString:atIndex: 21 //创建一个可变字符串str3 22 NSMutableString *str3 = [[NSMutableString alloc]initWithString:@"zhangsan"]; 23 [str3 insertString:@"---" atIndex:5]; 24 NSLog(@"%@",str3);//str3 = zhang---san; 25 26 // 拼接:appendFormat: 27 //str3必须为可变字符串 28 [str3 appendFormat:@"www"]; 29 //[str3 appendString:@"one"]; 30 NSLog(@"%@",str3); 31 32 33 // 移除:deleteCharactersInRange: 34 [str3 deleteCharactersInRange:NSMakeRange(5, 3)]; 35 NSLog(@"%@",str3); 36 37 // 替换:replaceCharactersInRange: withString: 38 [str3 replaceCharactersInRange:NSMakeRange(8, 3) withString:@" love "]; 39 NSLog(@"%@",str3); 40 41 // 截取:substringWithRange: 0为第一个位置 42 NSString *str4 = [str3 substringFromIndex:5]; 43 NSLog(@"%@",str4); //form冲那个位置开始 44 NSString *str5 = [str4 substringToIndex:8]; 45 NSLog(@"%@",str5); //开头到那个位置 46 NSString *str6 = [str3 substringWithRange:NSMakeRange(0, 8)]; 47 NSLog(@"%@",str6); //起点位置和 长度;