NSMutableString 类 继承NSString类,那么NSString 提供的方法在NSMutableString中基本都可以使用,NSMutableString好比一个字符串链表,它可以任意的动态在字符串中添加字符串 删除字符串 指定位置插入字符串,使用它来操作字符串会更加灵活。
1 // Do any additional setup after loading the view, typically from a nib. 2 NSMutableString * str = [[NSMutableString alloc] init]; 3 4 //添加普通的字符串 5 [str appendString:@"aaa"]; 6 7 //添加字符串 整型 字符型 8 [str appendFormat:@"我的名字:%@ 我的年龄:%d 我的邮箱:%s",@"雨松MOMO", 25,"xuanyusong@gmail.com"]; 9 10 NSLog(@"str = %@",str);
输出:
2013-12-24 15:30:40.082 Helloworld20131021_NSMutableString[2908:c07] str = aaa我的名字:雨松MOMO 我的年龄:25 我的邮箱:xuanyusong@gmail.com
2.字符串中删除元素
1 //创建字符串 2 NSMutableString *str1 = [NSMutableString stringWithString:@"雨松MOMO喜欢哇咔咔~"]; 3 4 //删除字符串中含"雨松"的字符 5 [str1 deleteCharactersInRange: [str1 rangeOfString: @"雨松"]]; 6 7 NSLog(@"str1 = %@",str1);
输出:
2013-12-24 15:30:40.083 Helloworld20131021_NSMutableString[2908:c07] str1 = MOMO喜欢哇咔咔~
3.字符串插入
1 //创建字符串 2 NSMutableString *str2 = [NSMutableString stringWithString:@"雨松MOMO喜欢哇咔咔~"]; 3 4 //在str第10位插入字符串 5 [str2 insertString:@"与小可爱" atIndex:10]; 6 7 NSLog(@"str2 = %@",str2);
输出:
2013-12-24 15:30:40.084 Helloworld20131021_NSMutableString[2908:c07] str2 = 雨松MOMO喜欢哇咔与小可爱咔~
4.字符串拷贝
1 2 //创建字符串 3 NSMutableString *str3 = [NSMutableString stringWithString: @"字符串1"]; 4 NSMutableString *str4; 5 6 //字符串赋值 7 str4 = str3; 8 9 [str4 appendString: @" 和字符串2"]; 10 11 NSLog (@"str3= %@", str3); 12 13 NSLog (@"str4 = %@", str4);
输出:
2013-12-24 15:30:40.084 Helloworld20131021_NSMutableString[2908:c07] str3= 字符串1 和字符串2
2013-12-24 15:30:40.085 Helloworld20131021_NSMutableString[2908:c07] str4 = 字符串1 和字符串2
5.字符串与指定类型转换
1 //字符串转整型 2 NSString *str0 = @"1121"; 3 //NSString *str0 = @"中国"; 4 5 //把字符串强转成整型 6 int i = [str0 intValue]; 7 8 NSLog (@"转换后:%i", i); 9 10 //字符串转interger 11 NSString *str5 = @"1985"; 12 // NSString *str1 = @"中国"; 13 14 //把字符串强转成interger 15 NSInteger ii = [str5 integerValue]; 16 17 NSLog (@"转换后:%i", ii); 18 19 //字符串转double 20 NSString *str6 = @"3.145926"; 21 //NSString *str2 = @"中国"; 22 23 //把字符串强转成double 24 double d = [str6 doubleValue]; 25 26 NSLog (@"转换后:%f", d); 27 28 //字符串转float 29 NSString *str7 = @"3.145926"; 30 //NSString *str3 = @"中国"; 31 //把字符串强转成float 32 33 double f = [str7 floatValue]; 34 35 NSLog (@"转换后:%f", f); 36 37 NSString *str8 = @"中国"; 38 39 //把字符串强转成整型 40 int i8 = [str8 intValue]; 41 42 NSLog (@"转换后:%i", i8);
输出:
2013-12-24 15:30:40.085 Helloworld20131021_NSMutableString[2908:c07] 转换后:1121
2013-12-24 15:30:40.086 Helloworld20131021_NSMutableString[2908:c07] 转换后:1985
2013-12-24 15:30:40.086 Helloworld20131021_NSMutableString[2908:c07] 转换后:3.145926
2013-12-24 15:30:40.087 Helloworld20131021_NSMutableString[2908:c07] 转换后:3.145926
2013-12-24 15:30:40.087 Helloworld20131021_NSMutableString[2908:c07] 转换后:0