Objective-C Foundation框架实践——NSMutableString(一)

     NSMutableString是属于可变字符串,有很多NSString没有的方法,我们来实现一下:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
  
    
    //可变字符串是字符串的子类;
    NSMutableString *mStr = [[NSMutableString alloc] initWithCapacity:10];
    [mStr setString:@"Hello"];
    NSLog(@"%@",mStr);
    
    //追加字符串;
    [mStr appendString:@" iOS"];
    NSLog(@"%@",mStr);
    
    //也可以格式化追加字符串;
    int a = 9;
    [mStr appendFormat:@"%d",a];
    NSLog(@"%@",mStr);
    
    
    //替换
    //注意:这里的替换和NSString方法中的替换不一样,NSString中的替换只是生成了原来字符串的一个拷贝而已,然后修改这个拷贝;
    //NSMutableString中的替换是真正的把原来的字符串中的某一部分替换;
    
    NSMutableString *mStr2 = [[NSMutableString alloc] initWithCapacity:10];
    [mStr2 setString:@"abcdefghijk"];
    
    //根据位置和长度创建range;
    NSRange range1 = NSMakeRange(0, 3);
    [mStr2 replaceCharactersInRange:range1 withString:@"ABC"];
    NSLog(@"mStr2 = %@",mStr2);
    
    //根据字符串查找确定range;
    NSRange range2 = [mStr2 rangeOfString:@"ijk"];
    [mStr2 replaceCharactersInRange:range2 withString:@"IJK"];
    NSLog(@"mStr2 = %@",mStr2);

    
    
    //插入字符串;
    NSMutableString *mStr3 = [[NSMutableString alloc] initWithCapacity:10];
    [mStr3 setString:@"abcdef"];
    
    [mStr3 insertString:@"ABC" atIndex:3];
    NSLog(@"mStr3 = %@",mStr3);
    
    
    //删除字符串;
    NSMutableString *mStr4 = [[NSMutableString alloc] initWithCapacity:10];
    [mStr4 setString:@"abcdef"];
    
    NSRange range3 = [mStr4 rangeOfString:@"cd"];
    [mStr4 deleteCharactersInRange:range3];
    NSLog(@"mStr4 = %@",mStr4);
    
    
    
    
  }
    return 0;
}

Objective-C Foundation框架实践——NSMutableString(一)_第1张图片

.


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

你可能感兴趣的:(ios,Objective-C,Foundation)