NSString本身不允許修改內容及字符串的長度,如果要修改的話,可以使用NSMutableString。
NSMutableString是NSString的子類,所以,所有NSString的方法都適用於NSMutableString。
[cpp]
NSString *str1 = @"Welcome,same!";
NSString *str2,*str3;
NSMutableString *mstr;
NSRange range;
mstr = [NSMutableString stringWithString:str1];
NSLog(@"%@",mstr);
[mstr insertString:@"back " atIndex:9];
NSLog(@"%@",mstr);
[mstr insertString:@"How are you" atIndex:[mstr length]];
NSLog(@"%@",mstr);
[mstr appendString:@" in there?"];
NSLog(@"%@",mstr);
[mstr deleteCharactersInRange:NSMakeRange(29,9)];
NSLog(@"%@",mstr);
range = [mstr rangeOfString:@"How are you?"];
if(range.location != NSNotFound){
[mstr deleteCharactersInRange:range];
NSLog(@"%@",mstr);
}
[mstr setString:@"Welcome,Sam!"];
NSLog(@"%@",mstr);
NSString *str1 = @"Welcome,same!";
NSString *str2,*str3;
NSMutableString *mstr;
NSRange range;
mstr = [NSMutableString stringWithString:str1];
NSLog(@"%@",mstr);
[mstr insertString:@"back " atIndex:9];
NSLog(@"%@",mstr);
[mstr insertString:@"How are you" atIndex:[mstr length]];
NSLog(@"%@",mstr);
[mstr appendString:@" in there?"];
NSLog(@"%@",mstr);
[mstr deleteCharactersInRange:NSMakeRange(29,9)];
NSLog(@"%@",mstr);
range = [mstr rangeOfString:@"How are you?"];
if(range.location != NSNotFound){
[mstr deleteCharactersInRange:range];
NSLog(@"%@",mstr);
}
[mstr setString:@"Welcome,Sam!"];
NSLog(@"%@",mstr);
運行結果:
Welocome,Sam!
Welocome,back Sam!
Welocome,back Sam!How are you
Welocome,back Sam!How are you in there?
Welocome,back Sam!How are you?
Welocome,back Sam!
作者:ztp800201