NSMutableString继承NSString
所有NSString类的方法NSMutableString都可以使用
NSMutableString是可修改的字符串,对象可以在原来的基础商家进行修改,不需要重新定义新的字符串对象,原对象的地址和修改后对象的地址是同一块地址
//
// main.m
// IOS150610_ObjectiveC_NSMutableString
//
// Created by Peng Junlong on 15/6/10.
// Copyright (c) 2015年 Peng Junlong. All rights reserved.
//
//***************************
//* *
//* NSMutableString操作 *
//* *
//***************************
#import <Foundation/Foundation.h>
//NSMutableString接触NSString
//所有NSString类的方法NSMutableString都可以使用
//NSMutableString是可修改的字符串,对象可以在原来的基础商家进行修改,不需要重新定义新的字符串对象
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建指定容量大小的字符串对象
/* In addition to these two, NSMutableString responds properly to all NSString creation methods.
*/
//- (NSMutableString *)initWithCapacity:(NSUInteger)capacity;
//+ (NSMutableString *)stringWithCapacity:(NSUInteger)capacity;
NSMutableString *mutableStr = [[NSMutableString alloc] initWithCapacity:20];//空的
NSLog(@"%@",mutableStr);
//替换指定范围内的字符
/* NSMutableString primitive (funnel) method. See below for the other mutation methods.
*/
//- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString;
NSMutableString *mutableStr1 = [[NSMutableString alloc] initWithString:@"Hello world China"];
[mutableStr1 replaceCharactersInRange:NSMakeRange(6, 5) withString:@"shangHai"];
NSLog(@"mutableStr1 = %@",mutableStr1); //结果:mutableStr1 = Hello shangHai China ,直接修改了mutableStr1的内容
//在指定位置增加字符串
//- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
NSMutableString *mutableStr2 = [[NSMutableString alloc] initWithFormat:@"Hello world China"];
[mutableStr2 insertString:@"你好" atIndex:6];
NSLog(@"mutableStr2 = %@",mutableStr2); //结果:mutableStr2 = Hello 你好world China
//删除指定范围内的字符
//- (void)deleteCharactersInRange:(NSRange)range;
NSMutableString *mutableStr3 = [NSMutableString stringWithUTF8String:"ShangHai Hello world China"];
[mutableStr3 deleteCharactersInRange:NSMakeRange(9, 5)];
NSLog(@"mutableStr3 = %@",mutableStr3); //结果:mutableStr3 = ShangHai world China
//追加字符串
//- (void)appendString:(NSString *)aString;
NSMutableString *mutableStr4 = [NSMutableString stringWithString:@"Hello World"];
[mutableStr4 appendString:@" Shanghai China"];
NSLog(@"mutableStr4 = %@",mutableStr4); //结果:mutableStr4 = Hello World Shanghai China
//格式化追加字符串
//- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
NSMutableString *mutableStr5 = [NSMutableString stringWithFormat:@"%s%d","HelloWorld",345];
[mutableStr5 appendFormat:@"%.3f%@",3.14,@"China"];
NSLog(@"mutableStr5 = %@",mutableStr5); //结果:mutableStr5 = HelloWorld3453.140China
//设置字符串内容,将原对象内容清空重新设置
//- (void)setString:(NSString *)aString;
NSMutableString *mutableStr6 = [[NSMutableString alloc] initWithString:@"Hello World China"];
[mutableStr6 setString:@"Hello China"];
NSLog(@"mutableStr6 = %@",mutableStr6); //结果:mutableStr6 = Hello China
}
return 0;
}