程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Objective-c NSMutableString 可變字符串

Objective-c NSMutableString 可變字符串

編輯:C++入門知識

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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved