Objective-c语言 字符串类NSMutableString用法
NSMutableString 是NSString 的子类,NSMutableString有很多方法,下面是总结的几种常用的方法:
stringWithString:,类级构造方法创建NSString对象;
insertString:,插入字符串,不会创建新的对象;
appendString:,追加字符串,不会创建新的对象;
deleteCharactersInRange:,在一个范围内删除字符串,不会创建新的对象;
replaceCharactersInRange: withString:,替换字符串,不会创建新的对象。
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *str1 = @"Objective C"; NSString *search,*replace; NSMutableString *mstr; NSRange substr; //从不可变的字符创建可变字符串对象 mstr = [NSMutableString stringWithString: str1]; NSLog(@" %@", mstr); //插入字符串 [mstr insertString: @ " Java" atIndex: 9]; NSLog(@" %@", mstr); //具有连接效果的插入字符串 [mstr insertString: @ " and C++"atIndex: [mstr length]]; NSLog(@" %@", mstr); //字符串连接方法 [mstr appendString: @ " and C"]; NSLog(@" %@", mstr); //使用NSRange删除字符串 [mstr deleteCharactersInRange:NSMakeRange(16, 13)]; NSLog(@" %@", mstr); //查找字符串位置 substr = [mstr rangeOfString: @ "string B and"]; if (substr.location != NSNotFound) { [mstr deleteCharactersInRange: substr]; NSLog(@" %@", mstr); } //直接设置可变字符串 [mstr setString: @ "This is string A "]; NSLog(@" %@", mstr); [mstr replaceCharactersInRange: NSMakeRange(8, 8) withString: @ "a mutable string "]; NSLog(@" %@", mstr); //查找和替换 search = @"This is "; replace = @"An example of "; substr = [mstr rangeOfString:search]; if (substr.location != NSNotFound) { [mstr replaceCharactersInRange:substr withString: replace]; NSLog(@" %@", mstr); } //查找和替换所有的情况 search = @"a"; replace = @"X"; substr = [mstr rangeOfString: search]; while (substr.location != NSNotFound) { [mstr replaceCharactersInRange:substr withString: replace]; substr = [mstr rangeOfString: search]; } NSLog(@" %@", mstr); [pool drain]; return 0; }运行结果如下:
2011-09-08 16:35:26.320 2.10.1-2[3124:a0f] Objective C 2011-09-08 16:35:26.323 2.10.1-2[3124:a0f] Objective Java C 2011-09-08 16:35:26.324 2.10.1-2[3124:a0f] Objective Java C and C++ 2011-09-08 16:35:26.324 2.10.1-2[3124:a0f] Objective Java C and C++ and C 2011-09-08 16:35:26.325 2.10.1-2[3124:a0f] Objective Java CC 2011-09-08 16:35:26.325 2.10.1-2[3124:a0f] This is string A 2011-09-08 16:35:26.326 2.10.1-2[3124:a0f] This is a mutable string 2011-09-08 16:35:26.326 2.10.1-2[3124:a0f] An example of a mutable string 2011-09-08 16:35:26.327 2.10.1-2[3124:a0f] An exXmple of X mutXble string我们解释主要代码。语句[mstr deleteCharactersInRange:NSMakeRange(16, 13)]是删除指定范围的字符串,函数NSMakeRange 是创建NSRange结构体,其中第一个参数是位置,第二个参数是长度;语句[mstr replaceCharactersInRange: NSMakeRange(8, 8)withString: @ "a mutable string "]替换指定访问的字符串;语句[mstr deleteCharactersInRange: substr]是删除指定范围的字符串。
android 技术交流QQ群:108614806