Object-C 可变字符串
NSMutableString 可变字符串
可变字符串 ‘NSMutableString’ 是继承于不可变字符串’不可变字符串’。即意味着,前面所讲的关于不可变字符串的操作都适用于可变字符串。
1.NSMutableString 初始化的5个方法:
NSMutableString *mString = [NSMutableString stringWithString:@"nihao"];
//格式化生成可变字符串
NSMutableString *mString1 = [NSMutableString stringWithFormat:@"hello"];
//由本地文件读取字符串
NSMutableString *mString2 = [NSMutableString stringWithContentsOfFile:@"" encoding:NSUTF8StringEncoding error:nil];
//有网络文件读取字符串
NSMutableString *mString3 = [NSMutableString stringWithContentsOfURL:[NSURL URLWithString:@""] encoding:NSUTF8StringEncoding error:nil];
//可变字符串独特初始化方式,初始化一个空间为100的空的可变字符串
NSMutableString *mString4 = [[NSMutableString alloc]initWithCapacity:100];
2.NSMtuableString 的增加、替换、删除 操作
不可变字符串的API可变字符串都具备
NSMutableString *targetString = [NSMutableString stringWithString:@"你麻痹"];
NSRange range = [targetString rangeOfString:@"麻痹"];
//增加
//在指定位置去插入一个字符串
[targetString insertString:@"你是sb莫" atIndex:targetString.length ] ;
NSLog(@"tagetString = %@",targetString);
//在字符串的末尾添加一个字符串
[targetString appendString:@"byebye"];
NSLog(@"%@",targetString);
//在字符串的末尾添加多个字符串
[targetString appendFormat:@"%@%@",@"asdf",@"boom boom"];
NSLog(@"%@",targetString);
//替换
range = [targetString rangeOfString:@"sb"];
[targetString replaceCharactersInRange:range withString:@"&&"];
NSLog(@"%@",targetString);
//删除
[targetString deleteCharactersInRange:NSMakeRange(0, 3)];
NSLog(@"%@",targetString);