// // main.m // 字符串-可变字符串 // // Created by zhangqs008 on 14-2-13. // Copyright (c) 2014年 zhangqs008. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSString *str1=@"this is string A"; NSString *search; NSString *replace; NSMutableString *mutableStr; NSRange subStr; //01.从不可变字符串创建可变字符串 mutableStr=[NSMutableString stringWithString:str1]; NSLog(@"01 %@",mutableStr); //02.插入字符,注意:是直接修改的字符串对象,无返回值 [mutableStr insertString:@" mutable" atIndex:7]; NSLog(@"02 %@",mutableStr); //03.插入末尾进行有效拼接 [mutableStr insertString:@" and string B" atIndex:[mutableStr length]]; NSLog(@"03 %@",mutableStr); //04.直接用appendString [mutableStr appendString:@" and string C"]; NSLog(@"04 %@",mutableStr); //05.根据范围删除字符串 deleteCharactersInRange(从*开始,删除*个字符) [mutableStr deleteCharactersInRange:NSMakeRange(16,13)]; NSLog(@"05 %@",mutableStr); //06.查找然后将其删除 subStr=[mutableStr rangeOfString:@"string B and "]; if(subStr.location!=NSNotFound) { [mutableStr substringWithRange:subStr]; NSLog(@"06 %@",mutableStr); } //07.直接设置为可变字符串 [mutableStr setString:@"this is string A"]; NSLog(@"07 %@",mutableStr); //08.替换一些字符 [mutableStr replaceCharactersInRange:NSMakeRange(8, 8) withString:@"a mutable string"]; NSLog(@"08 %@",mutableStr); //09.查找和替换 search=@"this is"; replace=@"An example of"; subStr=[mutableStr rangeOfString:search]; if(subStr.location!=NSNotFound) { [mutableStr replaceCharactersInRange:subStr withString:replace]; NSLog(@"09 %@",mutableStr); } //10.查找和替换所有匹配项 search=@"a"; replace=@"X"; subStr=[mutableStr rangeOfString:search]; while (subStr.location!=NSNotFound) { [mutableStr replaceCharactersInRange:subStr withString:replace]; subStr=[mutableStr rangeOfString:search]; } NSLog(@"10 %@",mutableStr); //也可以这样写 [mutableStr replaceOccurrencesOfString:search withString:replace options:nil range:NSMakeRange(0, [mutableStr length])]; NSLog(@"10 %@",mutableStr); } return 0; }
输出结果:
2014-02-13 20:38:30.074 05.字符串-可变字符串[997:303] 01 this is string A
2014-02-13 20:38:30.076 05.字符串-可变字符串[997:303] 02 this is mutable string A
2014-02-13 20:38:30.079 05.字符串-可变字符串[997:303] 03 this is mutable string A and string B
2014-02-13 20:38:30.079 05.字符串-可变字符串[997:303] 04 this is mutable string A and string B and string C
2014-02-13 20:38:30.080 05.字符串-可变字符串[997:303] 05 this is mutable string B and string C
2014-02-13 20:38:30.080 05.字符串-可变字符串[997:303] 06 this is mutable string B and string C
2014-02-13 20:38:30.081 05.字符串-可变字符串[997:303] 07 this is string A
2014-02-13 20:38:30.081 05.字符串-可变字符串[997:303] 08 this is a mutable string
2014-02-13 20:38:30.081 05.字符串-可变字符串[997:303] 09 An example of a mutable string
2014-02-13 20:38:30.082 05.字符串-可变字符串[997:303] 10 An exXmple of X mutXble string
2014-02-13 20:38:30.082 05.字符串-可变字符串[997:303] 10 An exXmple of X mutXble string
Program ended with exit code: 0