1.创建对象
<1>便利构造器法
NSString *str1 = [NSString stringWithFormat:@"iPhone"];
<2>初始化构造方法
NSString *str2 = [[NSString alloc] initWithFormat:@"iPhone"];
2.求字符串长度
NSUInteger length = [str1 length];
NSLog(@"length = %lu", length);
unichar ch = [str1 characterAtIndex:6];
NSLog(@"%c", ch);
4.判断是否以指定的字符串开头或者以指定的字符串结尾
初始化一个字符串str4
NSString *str4 = [[NSStringalloc] initWithFormat:@"http://www.souhu.com"];
判断是否以http开头
BOOL isPrefix = [str4 hasPrefix:@"http"];
NSLog(@"isPrefix = %d", isPrefix);
判断是否以com结尾
BOOL isSuffix = [str4 hasSuffix:@"com"];
NSLog(@"isSuffix = %d", isSuffix);
查找指定字符串com的范围
NSRange range = [str4 rangeOfString:@"com"];
NSLog(@"%@", NSStringFromRange(range));
输出为{17,3}.因为字符c下标为17, com的大小为3
5.字符串的截取
1>获取给定下标之后后的字串,包含指定下标对应的字符.
NSString *str5 =[NSString stringWithFormat:@"lanouisabigcompany"];
NSString *subString1 = [str5 substringFromIndex:5];
NSLog(@"%@", subString1);
输出为:isabigcompany 注意包含从下标5开始的字符: i
2>获取给定下标之前的子串,从下标为1开始,但是不包括指定下标对应的字符.
NSString *substring2 = [str5 substringToIndex:1];
NSLog(@"%@", substring2);
输出为:l 注意不包含开始的下标1的字符
3>获取指定范围内的子串.
NSString * substring3 = [str5 substringWithRange:NSMakeRange(0, 5)];
NSLog(@"%@", substring3);
输出结果为:lanoui
7 . 字符串拼接
NSString *str1 = [NSString stringWithFormat:@"lanou"]; //初始化
拼接"hennan"
NSString *substring1 = [str1 stringByAppendingString:@"henan"];
NSLog(@"substring = %@", substring1);
输出结果为:lanouhenan
stringByAppendingFormat可以添加格式
NSString *substring2 = [str1 stringByAppendingFormat:@"henan%dban",9];
NSLog(@"sunstring2 = %@", substring2);
输出结果为:lanouhenan9ban
NSString *substring3 = [str1stringByAppendingFormat:@"%@", str1];
NSLog(@"sunstring3 = %@", substring3);
输出结果为:lanoulanou
8. 替换字符串
将ou替换为牛逼
NSString *str1 = [NSString stringWithFormat:@"lanououououoooo"];
NSString *str = [str1 stringByReplacingOccurrencesOfString:@"ou"withString:@"牛逼"];
NSLog(@"str1 = %@", str);
输出结果为:lan牛逼牛逼牛逼牛逼oooo
将第一个ou替换为牛逼(替换某个区域的字符串)
NSMakeRange快速创建一个结构体
NSString *strr = [str1 stringByReplacingCharactersInRange:NSMakeRange(3, 2) withString:@"牛逼"];
NSLog(@"strr = %@", strr);
输出结果:lan牛逼ouououoooo 注意:3是开始的下标,2是范围
9 .字符串比较(重点)
<1> NSComparisonResult result = [@"319"compare:@"311"];
NSLog(@"result = %ld", result);
result = 1 (因为319 > 311)
<2> NSComparisonResult result = [@"319"compare:@"319"];
NSLog(@"result = %ld", result);
result = 0 (因为319 = 311)
<3> NSComparisonResult result = [@"318"compare:@"319"];
NSLog(@"result = %ld", result);
result = -1 (因为318=<311)
10.字符串与数值类型转换
int value = [@"1a23bbb" intValue];
NSLog(@"%d", value);
结果为:1
从第一个字符开始,如果在遇到除空格之外的字符时,将空格忽略掉,继续往下找,直到遇到非数字时结束
11.数字转为字符串对象
NSString *str = [NSString stringWithFormat:@"%d",9];
NSLog(@"str = %@", str);
结果为:9
12.大小写转换操作
将@"lan OU"全部转为大写
NSString *upper = [@"lan OU" uppercaseString];
NSLog(@"upper = %@", upper);
结果为:LAN OU
将@"lan OU"全部转为小写
NSString *lower = [@"lan OU" lowercaseString];
NSLog(@"lower = %@", lower);
结果为:lan ou
将@"lan OU"每个单词的首字母大写
NSString *shou = [@"lan OU" capitalizedString];
NSLog(@"shou = %@", shou);
结果:Lan Ou