NSMutableString
- NSMutableString和NSString的区别
- NSString是不可变的,里面的文字内容是不能修改的
- NSMutableString是可变的,里面的文字内容可以随时更改
- NSMutableString能使用NSString的所有方法
字符串中的可变和不可变
- 不可变:指字符串在内存中占用的存储空间固定,并且存储的内容不能发生变化
NSString *str = @"123";
- 可变:指字符串在内存中占用的存储空间可以不固定,并且存储的内容可以修改
NSMutableString *str = [NSMutableString stringWithString:@"123123"];
NSMutableString常用方法
- - (void)appendString:(NSString *)aString;
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
[strM appendString:@"123"];
- - (void)appendFormat:(NSString *)format, ...;
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
[strM appendFormat:@"/age = %zd", 10];
- - (void)deleteCharactersInRange:(NSRange)range;
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
NSRange range = [strM rangeOfString:@"/age"];
[strM deleteCharactersInRange:range];
- - (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
[strM insertString:@"aaa" atIndex:1];
- - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString;
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
[strM replaceCharactersInRange:range2 withString:@"bbb"];
- - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
- target:需要替换的字符串
- replacement:用来替换的字符串
- options:替换时的搜索方式,默认就可以,传入0
- searchRange:搜索范围
NSMutableString *strM = [NSMutableString stringWithString:@"123123"];
[strM replaceOccurrencesOfString:@"bbb" withString:@"nnn" options:0 range:range2];
注意事项
- @"123"这种方式创建的字符串始终都是NSString,是不可变的
// str的真实类型还是NSString
NSMutableString *str = @"123";