代码:
1 #import <Foundation/Foundation.h> 2 3 int main(int argc, const char * argv[]) { 4 @autoreleasepool { 5 NSMutableString *mustr1=[[NSMutableString alloc]init]; 6 NSMutableString *mustr2=[[NSMutableString alloc]initWithFormat:@"Hello"]; 7 NSMutableString *mustr3=[[NSMutableString alloc]init]; 8 //赋值 9 NSString *str1=@"Welcom to OC"; 10 mustr1=[[NSMutableString alloc]initWithString:str1]; 11 //NSMutableString *[email protected]"Hello"; 错误的赋值法,不能将字符串常量直接赋值给NSMutableString 12 //替换字符串 13 NSRange rang1=[mustr1 rangeOfString:@"OC"]; 14 [mustr1 replaceCharactersInRange:rang1 withString:@"Objective-C"]; 15 NSLog(@"mustr1=%@",mustr1); 16 //插入字符串 17 [mustr1 insertString:@" students" atIndex:6]; //在指定位置插入字符串 18 [mustr2 appendString:@" teacher!"]; //在末尾插入字符串 19 [mustr3 appendFormat:@"Hey!%@",str1]; //格式化插入字符串 20 NSLog(@"mustr1=%@,mustr2=%@,mustr3=%@",mustr1,mustr2,mustr3); 21 //指定位置删除字符串 22 [mustr1 deleteCharactersInRange:NSMakeRange(7, 9)]; 23 NSLog(@"mustr1=%@",mustr1); 24 //查找删除字符串 25 NSRange rang2=[mustr2 rangeOfString:@" teacher"]; 26 if(rang2.location!=NSNotFound){ 27 [mustr2 deleteCharactersInRange:rang2]; 28 } 29 NSLog(@"%@",mustr2); 30 //重新赋值 31 [mustr1 setString:str1]; 32 NSLog(@"%@",mustr1); 33 } 34 return 0; 35 }
时间: 2024-10-18 06:32:21