当前位置:编程学习 > C/C++ >>

Objective-c NSMutableString 可变字符串

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

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,