一.可变字符串创建
1.非法创建的方式
NSMutalbeString *mStr = @"abc";
2.通过构造方法创建可变字符串
NSMutableString *mStr1 = [[NSMutableString alloc]initWithString:@"abc"]; NSMutableString *mStr2 = [[NSMutableString alloc]initWithUTF8String:"abc"]; NSMutableString *mStr3 = [[NSMutableString alloc]initWithFormat:@"%@%c",@"ab",'c'];
3.通过类方法创建可变字符串
NSMutableString *mStr4 = [NSMutableString stringWithString:@"abc"]; NSMutableString *mStr5 = [NSMutableString stringWithUTF8String:"abc"]; NSMutableString *mStr6 = [NSMutableString stringWithFormat:@"%@%c",@"ab",'c'];
二.可变字符串特性
首先创建一个空的可变字符串
NSMutableString *mStr = [[NSMutableString alloc]init];
1.添加字符串(setString,appendString,insertString)
[mStr setString:@"abc"]; [mStr appendString:@"def"]; [mStr insertString:@"gh" atIndex:3]; NSLog(@"mStr is %@",mStr);
输出结果:
2016-06-27 11:43:51.242 OcTest[698:466304] mStr is abcghdef Program ended with exit code: 0
2.删除指定位置的字符串(deleteCharactersInRange)
[mStr deleteCharactersInRange:NSMakeRange(4, 3)]; NSLog(@"mStr is %@",mStr);
输出结果:
2016-06-27 11:46:37.775 OcTest[708:481615] mStr is abcgf Program ended with exit code: 0
3.查询方法和NSString方法一样(rangeOfString)
4.替换指定范围内的字符串(replaceCharactersInRange)
[mStr replaceCharactersInRange:NSMakeRange(2, 2) withString:@"XXXXXX"]; NSLog(@"mStr is %@",mStr);
输出结果:
2016-06-27 11:51:16.773 OcTest[738:503275] mStr is abXXXXXXf Program ended with exit code: 0
未来的你会感谢今天努力的自己
------Alen