NSMutableString是NSString的子类
NSString是不可变的,里面的文字是不能进行修改的
NSMutableString是可变的,里面文字可以随时更改
字符串的可变和不可变
不可变:指的是字符串在内存中占用的存储空间固定,并且存储的内容不能发生变化
可变:指的是制服穿在你存中占用的存储空间可以不固定,并且存储的内容可以被修改
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *str=@"jace";//存储在常量区
- NSLog(@"%p",str);//地址为4038
- str=@"Rose";
- NSLog(@"%p",str);//地址为4078
- NSMutableString *str2=[NSMutableString stringWithFormat:@"jack"];
- NSLog(@"%p",str2);
- //字符串延展appendString,每次延展空间扩大
- [str2 appendString:@"&Rose"];
- NSLog(@"%p",str2);//地址一样
- }
- return 0;
- }
复制代码
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- //格式化延展
- //appendFormat
- NSMutableString *str1=[NSMutableString string];
- [str1 appendFormat:@"jpg%d",10];
- //删除range.location处range.lenth长度字符串
- //-(void)deleteCharactersInRange:(NSRange)range;
- NSMutableString *str2=[NSMutableString stringWithFormat:@"Lazy&jiangkeshanshan"];
- NSRange range=[str2 rangeOfString:@"jiangke"];
- [str2 deleteCharactersInRange:range];
- NSLog(@"%@",str2);
- //在location位置插入一个字符串
- //-(void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
- NSMutableString *str3=[NSMutableString stringWithFormat:@"lazy&"];
- NSRange range1=[str3 rangeOfString:@"&"];
- [str3 insertString:@"shanshan" atIndex:range1.location+1];
- NSLog(@"%@",str3);
- //使用aString替换range范围内字符串
- //-(void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString
- NSMutableString *str4=[NSMutableString stringWithFormat:@"lazy&miandian"];
- NSRange range2=[str4 rangeOfString:@"miandian"];
- [str4 replaceCharactersInRange:range2 withString:@"shanshan"];
- NSLog(@"%@",str4);
- //错误1:给可变字符串赋值了不可变内容
- // NSMutableString *str5=@"adb";
- //错误2:给str的string属性设为空
- // NSMutableString *str5=@"abc";
- // str5.string=@"";
- }
- return 0;
- }
复制代码
|
|