OC基础之字符串、数组、字典、集合

 *************************
 *********字符串**********
 *************************
 
 1、固定字符串
    1.初始化
        NSString * str = @"kermit";
        char * cStr = "中文";
        NSString * str1 = [[NSString alloc] initWithCString:cStr encoding: NSUTF8StringEncoding];
        NSString * str2 = [[NSString alloc] initWithFormat:@"format,%@ %d",@"字符串",10];
 
    2.获取字符串长度
        NSUInteger length = [str length];
 
    3.获取单个字符
        unichar ch = [str characterAtIndex:i];//打印unichar格式符 "%C"
 
    4.获取子串
        NSString substr = [str substringFromIndex:i];   //从索引值i开始截取到str的最后,存入substr(包含索引值)
        NSString substr2 = [str substringToIndex:i];    //从str的第一个元素开始截取到i,存入substr(不包含索引值元素)
        NSRange range = {a,b};  //NSUInteger location(range.location == a) 起始位置 NSUInteger length(range.length == b) 截取的长度
 
    5.根据字符串,获得该字符串在另一个字符串中的索引范围
        NSString * str = @"kermit";
        NSString * str2 = @"www.kermit.com";
        NSRange range = [str2 rangeOfString:str];
 
    6.判断字符串是否为空
        NSString * str = @"";   //[str length] == 0; 为空
        NSString * str1 = nil;  //str == nil; 为空
        NSString * str2 = @" "; //str == ' ';含有字符空格,不为空
 
    7.判断是否以指定格式开头,或结尾
        NSString * str = @"www.baidu.com";
        NSString * str1 = @"hello.c";
        BOOL hasPre = [str hasPrefix:@"www."];  //判断是否是网址 返回值BOOL类型
        BOOL hasSuf = [str1 hasSuffix:@".c"];   //判断是否是 .c 文件
 
    8.判断两个字符串是否相等
        NSString * str = @"kermit";
        NSString * str1 = @"kermit";
        
        //方法一
        if ([str isEqualToString:str1]) {
            NSLog(@"==");
        } else {
            NSLog(@"!=");
        }
        //方法二
        NSComparisonResult result = [str compare:str1]; //compare比较的时ASCII
        switch (result) {
            case NSOrderedAscending:
                NSLog(@"<");
                break;
            case NSOrderedDescending:
                NSLog(@">");
                break;
            case NSOrderedSame:
                NSlog(@"==");
                break;
        }
 
    9. int/float/double/char ---> NSString  (多个数据拼接成一个字符串 @"%d%f%c%@" )
        int a = 3;
        float b = 3.14;
        double c = 3.141592654321;
        char d = 'm';
        NSString * str = [[NSString alloc] initWithFormat:@"%d %.2f %.5f %C",a,b,c,d];
        // str == @"33.143.141592654321m";
 
    10. NSString ---> int/float/double  //要保证字符串中的字符能正确转换成指定格式 eg: [@"3.14" intValue] 失败
        NSStrig * str = @"100";
        int a = [str intValue];
        NSString * str1 = @"3.14";
        float b = [str1 floatValue];
        NSString * str2 = @"3.141592654321";
        double c = [str2 doubleValue];
 
    11.大小写转换(因为原字符串是不可变,所以要用一个新的字符串(不可变)去接收)
        NSString * str = @"kermit";
        NSString * str1 = @"kermit";
        NSString * str00 = [str uppercaseString];
        NSString * str10 = [str lowercaseString];
        
        //首字母大写(被转换字母全部是大写,输出依旧是首字母大写,若字符串中含有空格,则空格后的第一个字母也是大写)
        NSString * str100 = [@"kermit" capitalizedString];    //输出 "kermit"
        NSString * str3 = @"bei jing me you";
        NSString * str30 = [str3 capitalizedString];    //输出 “Bei Jing Me You"
 
    12.在字符串末尾追加新的字符 (新字符串去接收)
        NSString * str = @"kermit";
        NSString * str1 = [str stringByAppendingString:@".com"];    //末尾只能追加固定内容的字符或字符串
 
    13.在指定范围添加(覆盖)新的字符串
        NSRange range = {4,0};  //追加在 range.location 处
        NSRange range1 = {4,1}; //追加在 range1.location 处,覆盖长度 range.length 注意:覆盖的长度不能大于range1.location后面剩余的长度
        NSString * str = @"www..com";
        NSString * str2 = [str stringByReplacingCharacterInRange:range WithString: @"baidu"];
 
    14.使用新的字符串替换原有的字符串
        NSString * str = @"www.kermit.com";
        NSString * str2 = [str stringByReplacingOccurencessOfString:@"kermit" withString:@"baidu"];
        //删除字符串中的空格
        NSString * str = @"ai wq ao mng";
        NSString * str1 = [str stringByReplacingOccurencessOfString:@" " withString:@""];
 
    15.字符串在文件中的读写
        //写入文件
        NSString * str = @"你好,世界。hello world.";
        NSString * path = @"@"/Users/kermit/Desktop/未命名文件夹/str.txt"";
        NSError * error;
        //writeToFile:(NSString *) atomically:(BOOL) encoding:(NSStringEncoding) error:(NSError *__autoreleasing *)
        [str writeToFile:path atomically:YES encoding:NSUIT8StringEncoding error:&error];
        if (error) {
            NSLog(@"写入失败",error);
        } else {
            NSLog(@"成功");
        }
 
        //读取字符串
        NSString * str1 = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        if (error == nil) {
            NSLog(@"%@",str);
        } else {
            NSLog(@"%@",error);
        }
 
 
 2、可变字符串
    1.初始化
        NSString * str = @"nutable str";
        NSMutableString * muStr = [[NSMutableString alloc] initWithString:str]; //muStr == @"mutable str";
 
    2.重置字符串
        NSMutableString * muStr1 = [[NSMutableString alloc] init];
        [muStr1 setString:@"kermit"];     //muStr1 == @"kermit";
        [muStr setString:@"kermit"];  //muStr == @"kermit";
 
    3.在末尾追加字符串
        [muStr1 appendString:@".com"];  //muStr1 == @"kermit.com";
        [muStr1 appendingFormat:@"%@%d%.2f",@"abc",5,2.3];  //muStr1 == @"kermit.comabc52.30";

    4.在指定位置插入字符串
        [muStr1 insertString:@"www." atIndex:0];    //muStr1 == @"www.kermit.comabc52.30";
 
    5.删除字符串(指定位置)
        NSRange range = {12,4}; //.com
        [muStr1 deleteCharacterInRange:range];  //muStr1 == @"www.kermitabc52.30";
 
 
 *************************
 **********数组************
 *************************
 
 1、固定数组
    1.创建数组(不可变数组创建后不可变,在创建的时候要初始化)
        //对象方法 [[NSArray alloc] initWithObjects:(id),nil]
        NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"2",@"2.3",@"a",nil];    //array == (one,2,"2.3",a);
        //类方法 [NSArray arrayWithObjects:(id),nil]
        NSArray * array1 = [NSArray arrayWithObjects:@"one",@"2",@"2.3",@"a",nil];  //array == (one,2,"2.3",a);
 
        //次方法最后一个元素必须是nil,如果数组中间存在 nil 元素,容易导致数据丢失
        NSString * str = nil;
        NSArray * array4 = [[NSArray alloc] initWithObjects:@"oe",@"2",str,@"t3",@"3.14", nil]; //array4 = (oe,2);
 
        //快速方法 @[(id)]
        NSArray * array3 = @[@"one#",@"23",@"2.3",@"a"];    //array = ("one#",23,"2.3",a);
 
    2.基本类型转换成数组对象
 
        //数组中可以存储不同类型的对象
        int i = 10;
        float f = 3.14;
        NSNumber * number = [NSNumber numberWithInt:i];
        NSNumber * number1 = [NSNumber numberWithFloat:f];
        NSArray * array = @[@"one",@"10",number,number1];   // array == (one,10,10,"3.14");
 
        //数组中存储的是对象的地址,数组中也可以存储数组的地址
        NSArray * array1 = @[@"1",@"2",@"3"];
        NSArray * array2 = @[array,array1];
 
    3.数组中自定义对象
        //创建三个对象(类以及创建)
        Person * p1 = [[Person alloc] initWithName:@"Jack" andAge:15];
        Person * p2 = [[Person alloc] initWithName:@"Tom" andAge:20];
        Person * p3 = [[Person alloc] initWithName:@"Lucy" andAge:18];
        NSArray array4 = @[p1,p2,p3];
 
    4.获取数组中的元素
        Person * p = [array4 objectAtIndex:0];  //name = Jack,age = 15
        Person * p = array4[0]; //快速方法
 
    5.数组中元素个数
        NSUInteger count = [array4 count];
        NSLog(@"%lu",count);
 
    6.判断数组中是否包含某个元素
        Person * p4 = [[Person alloc] initWithName:@"Tom" andAge:20];
        NSLog(@"p2=%p,p4=%p",p2,p4);    //p2和p4的地址不相同,p4为新对象
        if ([array4 containsObject:p4]) {
            NSLog(@"包含");
        } else {
            NSLog(@"不包含");
        }
        //不包含,p4不在array4中,即使内容相同,但是也不包含
 
 
        NSArray * array5 = @[@"one",@"two",@"three"];
        NSString * str2 = @"one";
        NSString * str4 = @"one";
        NSString * str3 = [[NSString alloc] initWithFormat:@"%@",@"two"];
        NSLog(@"%p %p %p %p",str2,str3,str4,array9[0]);  //0x100002088 0x6f777435 0x100002088
        //在创建字符串的时候会判断内存是否含有相同字符串,若有相同的则不会新开辟内存去存储,只把新的字符串指针指向那个地址,若没有相同的则就会新开辟空间去存储
        //但是 str3 是重新初始化 NSString,所以str3的地址是固定的 并不和array[1]的地址一样
        if ([array9 containsObject:str3]) {
            NSLog(@"包含");
        } else {
            NSLog(@"不包含");
        }
        //包含
    
    7.遍历数组
        NSArray * array = @[@"1",@"2",@"three",@"4"];
        //方法一
        for (int i=0; i<[array count]; i++) {
            NSLog(@"array[%d]=%@",i,array[i]);
        }
        //方法二
        for (id * str in array) {
            NSLog(@"%@",str);
        }
 
    8.数组排序(排序后放在一个新的NSArray数组中)
        NSArray * array = @[@"a",@"b",@"f",@"d",@"c"];
 
        //传入一个比较大小的方法 根据返回值来决定是否需要交换元素
        NSArray * array2 = [array sortedArrayUsingSelect:sel];
        SEL sel = @selector(compare:);  //a-b-c-d-f
        SEL sel2 = @selector(isGreatThan:); //a-b-c-d-f
        SEL sel3 = @selector(isLessThan:);  //f-d-c-b-a
 
        //block
        //返回值 (^名字)(参数列表)
        NSArray * array3 = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [obj1 compare:obj2];
        }];     //a-b-c-d-f
        NSArray * array4 = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [obj1 compare:obj2];
        }];     //f-d-c-b-a
 
 
 2、可变数组
    1.创建可变数组
        NSArray * array = @[@"one",@"two",@"three",@"four"];
        NSMutableArray * muArr = [[NSMutableArray alloc] initWithArray:array];
        NSMutableArray * muArr2 = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",nil];
 
    2.添加元素
        NSMutableArray * muArr3 = [[NSMutableArray alloc] init];
        [muArr3 addObject:@"one"];
 
    3.添加其他数组的元素
        [muArr3 addObjectsFromArray:array];
 
    4.在指定位置插入元素
        [muArr3 insetObject:@"a" atIndex:1];
 
    5.删除元素  会通过对象地址删除数组中所有的用同一个地址的对象
        [muArr removeObject:@"one"];    //删除数组中的所有指向"one"地址的元素
 
    6.通过索引方式删除对象(索引值不能数组越界)
        [muArr removeObjectAtIndex:0];
 
    7.删除所有元素
        [muArr removeAllObjects];
    
    8.交换数组元素    //- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;
         [muArr exchangeObjectAtIndex:i withObjectAtIndex:j]
 
 
 3、数组转换
    1.不可变数组到可变数组
        NSArray * array = @[@"one",@"two"];
        NSMutableArray * muArr = [[NSMutableArray alloc] initWithArray:array];  // [array mutableCopy];
    
    2.可变数组变成不可变数组
        [muArr copy]
 
 
 *************************
 **********字典************
 *************************
 
 1、不可变字典
    1.创建不可变字典
        NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",nil];
        //快速创建字典
        NSDictionary * dic1 = @{@"3":@"three",@"4":@"four"};
    
    2.字典可以存储任意类型的对象
        NSArray * array = @[@"one",@"333"];
        NSNumber * num = [NSNumber numberWithInt:10];
        NSDicitonary * dic2 = @{@"dic":dic,@"num":num,@"array":array};
 
    3.获取字典的长度(键的个数)
        NSUInteger count = [dic2 count];
 
    4.从字典中取值
        NSString * arr = [dic3 objectForKey:@"array"];
        //快速取值
        NSDictionary * dic4 = dic3[@"dic"];
        NSNumber * number = dic3[@"num"];
 
 
 2、可变字典
    1.创建可变字典
    NSMutableDictionary * muDic = [[NAMutableDictionary alloc] initWithObjectsAndKeys:@"one",@"1",nil];
    //向可变字典中添加不可变字典
    NSDictionary * dic = @{@"3":@"three"};
    NSMutableDictionary * muDic2 = [[NSMutableDictionary alloc] initWithDictionary:dic];
 
    2.向字典中插入数据
    [muDic2 setObject:@"two" forKey:@"2"];
 
    3.遍历字典
    NSArray * allKeys = [muDic2 allKeys];
    for (id key in allKeys) {
        NSLog(@"%@",key);
        id obj = muDic2[key];
        NSLog(@"%@",obj);
    }
 
    4.删除数据
    [muDic2 removeObjectForKey:@"2"];
 
    5.全部删除
    [muDic removeAllObjects];
 
 
 *************************
 **********集合************
 *************************
 
 //NSSet 是无序的,不能存储重复数据,可以用来去除重复数据
 //NSArray 是自然顺序
 1、不可变集合
    1.创建
        NSSet * set = [[NSSet alloc] initWithObjects:@"one",@"b",@"two",@"three",@"a"@"two",nil];
    
    2.个数
        NSUInteger count = [set count];
    
    3.判断是否包含某个对象
        BOOL isContation = [set contationObject:@"t"];
        if (isContation) {
            NSLog(@"contation");
        } else {
            NSLog(@"not contation");
        }
 
 
 2、可变集合
    1.创建
        NSMutableSet * muSet = [[NSMutableSet alloc] initWithObjects:@"1",@"2",@"3",nil];
 
    2.添加对象
        [muSet addObject:@"four"];
 
    3.删除对象
        [muSet removeObject:@"2"];
 
    4.删除所有对象
        [muSet removeAllObjects];
 
 
 *************************
 ********相互转换**********
 *************************
 

 1.数组-->集合
    NSSet * set = [[NSSet alloc] initWithArray:array];

 2.字典-->数组
    NSDictionary * dic = @{@"1":@"two",@"2":@"kk"};
    NSArray * keysArr = [dic allKeys];
    NSArray * valuaesArr = [dic allValues];

 3.字符串-->数组
    NSString * str = @"I am in shanghai";
    NSArray * strArr = [str componentsSeparatedByString:@" "];

 4.数组-->字符串
    NSString * str1 = [strArr componentsJoinedByString:@"-"];

你可能感兴趣的:(OC基础之字符串、数组、字典、集合)