Objective-C 字符串二 "可变字符串"

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        //可变字符串 NSMutableString
        NSMutableString *mString1 = [NSMutableString stringWithString:@"nihao"];
        NSLog(@"mString1 = %@",mString1);    //mString1 = nihao
        
        NSMutableString *mString2 = [NSMutableString stringWithFormat:@"hello%d",100];
        NSLog(@"mString2 = %@",mString2);    //mString2 = hello100
        
        NSString *string = [NSString stringWithString:@"haha"];
        NSLog(@"string = %@",string);        //string = haha
        
        //可变字符串独特初始化方法,初始化一个空间为100的可变字符串
        NSMutableString *tableString = [[NSMutableString alloc]initWithCapacity:100];
        
        NSMutableString *targetString = [NSMutableString stringWithString:@"呵呵、我靠"];
        NSRange range = [targetString rangeOfString:@"靠"];
        NSLog(@"range = %@",[NSValue valueWithRange:range]);   //range = NSRange: {4, 1}
        
        //替代
        [targetString replaceCharactersInRange:range withString:@"*"];
        NSLog(@"%@",targetString);                  // 呵呵、我*
        
        //增加
        //在指定的位置插入一个字符串
        [targetString insertString:@" 你是sb嘛?" atIndex:targetString.length];
        NSLog(@"targetString = %@",targetString);   // 呵呵、我* 你是sb嘛?
        
        
        //在字符串末端添加一个字符串
        [targetString appendString:@"boy boy"];
        NSLog(@"%@",targetString);   //呵呵、我* 你是sb嘛?boy boy
        
        [targetString appendFormat:@"%@%@",@"    haha",@"hehe"];
        NSLog(@"%@",targetString);   //呵呵、我* 你是sb嘛?boy boy    hahahehe
        
        //删除
        [targetString deleteCharactersInRange:NSMakeRange(0, 2)];    //从第一个起始开始 及 长度
        NSLog(@"%@",targetString);    //、我* 你是sb嘛?boy boy    hahahehe
      
    }
    return 0;
}

你可能感兴趣的:(Objective-C 字符串二 "可变字符串")