#import <Foundation/Foundation.h> #pragma mark - 创建可变字符串 void stringCreate(){ NSMutableString *str=[[NSMutableString alloc] initWithCapacity:10];//预分配是个空间,提高效率 //设置字符串的内容 [str setString:@"123"]; //连接字符串 [str appendFormat:@"age is %i and height is %.2f",27,175.5f]; [str appendString:@"添加结束"]; //字符串替换 NSRange range=[str rangeOfString:@"age"]; //找到当前字符串的位置 [str replaceCharactersInRange:range withString:@"年龄"]; //替换字符串 //插入字符串 [str insertString:@"我是插入的字符串" atIndex:2]; NSLog(@"可变字符串是:%@",str); [str release];//释放对象 } int main(int argc, const char * argv[]) { @autoreleasepool { stringCreate(); } return 0; }
结果:
2013-08-02 15:29:58.909 NSMutableString[1145:303] 可变字符串是:12我是插入的字符串3年龄 is 27 and height is 175.50添加结束
本文转自蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366480,如需转载请自行联系原作者