Foundation使用示例(NSString、NSMutableString 、NSArray、NSMutableArray 、NSDictionary 、NSMutableDictionary)

躍然發表於2015-12-18

1. NSString字串比較

void test(){

    NSString *str = @"ccd";  // 3

    NSString *str2 = @"bcde";// 4

    //比較兩個字串大小:
    //比較每個字元的ascii碼值
    //compare 比較字串
    //str > str2    1
    //    <         -1
    //    ==         0
    //       NSComparisonResult result =  [str compare:str2];

    //指定條件的字串比較
    //NSCaseInsensitiveSearch 不區分大小寫
    //預設的區分大小寫
    //        result = [str compare:str2 options:NSCaseInsensitiveSearch];

    //按照字元的個數進行比較
    NSComparisonResult result = [str compare:str2 options:NSNumericSearch];

    switch (result) {
        case NSOrderedAscending:
            NSLog(@"str < str2");
            break;
        case NSOrderedSame:
            NSLog(@"str == str2");
            break;
        case NSOrderedDescending:
            NSLog(@"str > str2");
            break;

        default:
            break;
    }

    //OC中字串比較的時候,可以加條件  區分大小寫  字元的個數
  }

2. NSString前字尾檢查及搜尋


void test(){

    NSString *url = @"http://asdfasdfasdfaasdfadsfaf";

    //判斷這個地址,是否是一個網址
    //1、 hasPerfix  檢查字串是否以另外一個字串開頭

    if([url hasPrefix:@"http://"]){

        NSLog(@"這是一個網址");

    }else{

        NSLog(@"這不是一個網址");

    }


    //2、檢查字尾
    // 需求,檢查是否是一張圖片   jpg   png  jpeg
    // 先檢是否是一個png的圖片
    NSString *str = @"logo.txt";  //logopng
    if([str hasSuffix:@".png"]||[str hasSuffix:@".jpg"]||[str hasSuffix:@".jpeg"]){

        NSLog(@"是圖片");

    }else {

        NSLog(@"不是圖片");

    }


     //字串的查詢
        NSString *str = @"asitxcastdfafsadfxyz asdfasdfsadfa sadf";

        // rangeOfString 作用是查詢子字串itcast在 str中第一次出現的位置
        // 如果找能夠查詢到字串,則返回子字串的位置資訊
        // 如果查詢不到,則返回的Range
        //                       位置 是一個特別大得數
        //                       length 0
        NSRange range = [str rangeOfString:@"itcast"];

        //NSNotFound 是一個最大的long 無符號數
        //如果查詢不到 range.location 是一個最大的long 無符號數
        if (range.location != NSNotFound) {
             NSLog(@"位置:%ld,長度:%ld",range.location,range.length);
        }else{

            NSLog(@"沒有查詢到");
        }



}

3. NSRange 的使用


/*
  NSRange 是一個結構體
  用來表示範圍
  有兩個成員變數: location 表示範圍的起始位置  length 表示範圍的長度

  NSRange的幾種建立方式:

  1)直接賦值

   NSRange range1 = {2,5};

  2)先定義後賦值

   NSrange range2;
   range2.location = 1;
   range2.length = 23;
 */

  //1)直接賦值

        NSRange range1 = {2,5};
        NSLog(@"loc = %ld,len = %ld",range1.location,range1.length);

  //2)先定義後賦值

        NSRange range2;
        range2.location = 1;
        range2.length = 23;
        NSLog(@"loc = %ld,len = %ld",range2.location,range2.length);

        //3)使用NSMakeRange建立一個NSRange型別的變數
        NSRange range3 = NSMakeRange(45, 3);
        NSLog(@"loc = %ld,len = %ld",range3.location,range3.length);

4. 字串的擷取和替換

void test(){

    NSString *str = @"aaaaaaabbbbbbbccccccdddddd";

    //從指定的位置出開始(包含此位置),到最後
    //substringFromIndex
    NSString *newStr = [str substringFromIndex:7];


    //從起始位置開始,到指定位置(不包含指定位置)結束
    newStr = [str substringToIndex:5];

    //擷取指定範圍的字串
    NSString *dateStr = @"2015-01-29 12:12:30";
    //獲取日期
    NSRange range = {0,10};

    //獲取時間
    range = NSMakeRange(11, 8);

    //獲取指定範圍的字串
    newStr = [dateStr substringWithRange:range];

    NSLog(@"%@",newStr);

}


void test2(){


    NSString *str = @"<imufeng>沐風科技</imufeng>";

    unsigned long loc = [str rangeOfString:@">"].location+1;
    unsigned long len = [str rangeOfString:@"</"].location - loc;

    NSLog(@"%ld,%ld",loc,len);

    NSRange range = {loc,len};

    NSString *newStr = [str substringWithRange:range];

    NSLog(@"newStr = %@",newStr);

}


void test3(){

//把imufeng  -->  ios
        NSString *str = @"<imufeng>沐風科技</imufeng>";
        //在str中 將所有的 imufeng 都替換成 ios
        //str stringByReplacingOccurrencesOfString:@"imufeng" withString:@"ios"

        NSString *newStr = [str stringByReplacingOccurrencesOfString:@"imufeng" withString:@"ios"];



        //將http:**ios.imufeng.cn*ios*images*content_25.jpg中的*替換為/
        str = @"http:**ios.imufeng.cn*ios*images*content_25.jpg";
        newStr = [str stringByReplacingOccurrencesOfString:@"*" withString:@"/"];


        //"  http:**  ios.imufeng.cn  *ios*images*  content_25.jpg " 的空格去掉,並且將*替換為/
        str= @"  http:**  ios.imufeng.cn  *ios*images*  content_25.jpg ";

        //先替換空格 空
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];

        newStr = [str stringByReplacingOccurrencesOfString:@"*" withString:@"/"];

        NSLog(@"%@",newStr);

}

5. 字串的其他用法


/**
 *  取出每一個字元
 */
void test1(){


    NSString *str = @"ios.itcast.cn";

    //1、獲取字串的長度
    //呼叫字串的length方法
    //str.length  ---->  [str length];
    NSLog(@"%ld",str.length);

    //2、獲取字元的每一個字元
    unsigned long len = str.length;

    for (int i=0; i<len; i++) {
        unichar c = [str characterAtIndex:i];
        printf("%c  ",c);
    }

}


/**
 *  字串的轉換問題
 */
void test2(){

    int a = 23;
    //把整形資料包裝成字串了
    NSString *s0 = [NSString stringWithFormat:@"%d",a];

    //字串和基本資料型別轉換問題
    NSString *s1 = @"12";    //12+2
    //        s1+2;
    NSString *s2 = @"2.3";
    NSString *s3 = @"345.678";

    //把字串轉換為 int型別
    int n1 = [s1 intValue];
    NSLog(@"n1 = %d",n1*34);

    //字串轉換為float
    float f1 = [s2 floatValue];
    NSLog(@"f1 = %f",f1+3);

    //把字串轉換為double型別
    double d1 = [s3 doubleValue];
    NSLog(@"d1 = %f",d1+3);

    //把OC的字串物件轉換為C語言的字串
    //@"xxxx"  %@      "xxxxx"  %s

    NSString *s4 = @"helloworld";
    const char *ss = [s4 UTF8String];

    printf("%s\n",ss);

    //把c的字串轉換為OC字串物件
    char ch[]="itcast";
    NSString *ocStr = [NSString stringWithUTF8String:ch];
    NSLog(@"%@",ocStr);

}


void test3(){

        NSString *str = @" itc ast ";

        //1、去除字串首尾的空格
        NSCharacterSet *set =[NSCharacterSet whitespaceCharacterSet];
        NSString *newStr = [str stringByTrimmingCharactersInSet:set];

        str= @"IOSitAcastIT";
        //2、取出字串的首尾大寫字元
        newStr  = [str stringByTrimmingCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet]];



        NSLog(@"-----%@-----",newStr);

}

6. NSMutableString


void test1(){

        //不可變的字串
        NSString *str = @"Jack";
        str = @"Rose";
        //擷取
        NSString *newStr = [str substringToIndex:2];
        NSLog(@"%@",newStr);


        //可變字串
        //建立一個空字串
        NSMutableString *str2 = [NSMutableString string];
        //給字串追加內容
        [str2 appendString:@"welcome"];
        [str2 appendString:@" to"];
        [str2 appendString:@" itcast!"];

        NSLog(@"%@",str2);

}

/**
 *  可變字串的常用的方法
 */
void test2(){

    //定義一個可變的字串
    //NSString  不可變
    //NSMutableString 可變
    NSMutableString *str = [NSMutableString string];
    //追加字串
    [str appendString:@"xxxxx"];

    int a = 10;
    float f1 = 3.14;
    char ch = 'x';
    NSString *it = @"imufeng";

    //格式化的追加字串
    [str appendFormat:@" a = %d, f1 = %.2f,ch = %c --->%@",a,f1,ch,it];

    NSRange range = {5,5};
    //刪除指定範圍的字串
    [str deleteCharactersInRange:range];


    //增加字串@“ios”到str字串中
    [str insertString:@"ios" atIndex:5];

    //替換字串
    [str replaceCharactersInRange:range withString:@"zzzzz"];

    //先查詢再替換
    //imufeng  iosios
    //                 查詢字串
    NSRange range2 = [str rangeOfString:@"imufeng"];
    //                 替換字串
    [str replaceCharactersInRange:range2 withString:@"iosios"];


    NSLog(@"%@",str);

}

-(void)test3(){

        //可變字串易犯的錯誤
        //1、給可變字串賦值了常量
        NSMutableString *str = @"xxxxx";
        // [str appendString:@"imufeng"];

        NSMutableString *str2 = [NSMutableString string];
        [str2 appendString:@"imufeng"];
        //2、通過string的屬性,可以修改字串的內容
        str2.string = @"xxxxxx";

        // str2 rangeOfString:<#(NSString *)#> options:0
        NSLog(@"%@",str2);

}

7. NSArray 的介紹和基本使用


-(void)test {

        //NSArray是OC中的陣列類
        //1、建立NSArray的方法
        /*

         + (instancetype)array;
         + (instancetype)arrayWithObject:(id)anObject;
         + (instancetype)arrayWithObjects:(id)firstObj, ...;
         + (instancetype)arrayWithArray:(NSArray *)array;
         + (id)arrayWithContentsOfFile:(NSString *)path; // 讀取一個xml檔案.
         + (id)arrayWithContentsOfURL:(NSURL *)url; // 讀取一個xml檔案.

         */
        //陣列的最後一個值,我們預設的初始化為nil,nil表示陣列結束了
        NSArray *array1 = [NSArray arrayWithObjects:@"1",@"2",nil,@"3",nil];

        //使用一個已經存在的陣列,建立另外一個陣列
        NSArray *arr2 = [NSArray arrayWithArray:array1];


        NSLog(@"%@,%@",array1,arr2);

        NSArray *arr3 = [[NSArray alloc] initWithObjects:@"one",@"two",@"four", nil];

        // NSLog(@"%@",array1[2]);
        NSLog(@"%@",arr3);

        //建立一個空陣列
        NSArray *arr4 = [NSArray array];
        NSLog(@"%@",arr4);
}

8. NSArray 讀寫檔案


void test(){

    //定義一個陣列
    NSArray *arr = @[@"1",@"2",@"3",@"4",@"5",@"six",@"seven",@"8"];

    //把陣列的內容儲存到檔案中
    //1)路徑     2)原子性     3)編碼      4)錯誤
    // writeToFile
    // .plist 是一個什麼檔案,它使一個資原始檔
    BOOL isSuccess = [arr writeToFile:@"/Users/apple/Desktop/arr.xml" atomically:YES];
    if (isSuccess) {
        NSLog(@"寫入成功!");
    }


}

// 2、從檔案中讀取資料,並且放到陣列中
-(void)test2(){

        // 1)路徑      2)類方法
        NSArray *arr2 = [NSArray arrayWithContentsOfFile:@"/Users/apple/Desktop/arr.xml"];

        NSLog(@"arr2 = %@",arr2);

}


9. NSArray 與字串


/**
 *  把陣列元素連線成一個字串
 */
void test(){

    //定義一個陣列
    NSArray *arr = @[@"1",@"2",@"3",@"4",@"5",@"six",@"seven",@"8"];

    //componentsJoinedByString 方法的作用是把陣列元素連成一個字串
    //連線字串的時候,還可以指定元素和元素之間的分隔符
    NSString *str = [arr componentsJoinedByString:@"-"];

    NSLog(@"%@",str);
}



void test2(){

        //@"400-517-517"
        NSString *tel = @"400-517-517";
        //componentsSeparatedByString
        //把tel這個字串 ,用 - 做分隔
        //把分隔後的每一部分存放到陣列中

        NSArray *arr = [tel componentsSeparatedByString:@"-"];

        NSLog(@"%@",arr);
}


10. NSMutableArray及基本使用


-(void)test{

        //NSMutableArray 建立方法

        //********** 陣列的建立方法 ************
        //1、可以建立空陣列
        NSMutableArray *arr = [NSMutableArray array];
        //定義一個長度為5的陣列
        NSMutableArray *arr2 = [[NSMutableArray alloc] initWithCapacity:5];
        //2、可以呼叫類方法,建立陣列
        NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:@"1",@"two",@"3", nil];
        //3、可以呼叫物件方法,建立陣列
        NSMutableArray *arr4 = [[NSMutableArray alloc] initWithObjects:@"1",@"3", nil];


        NSArray *array = @[@"1",@"10",@"100",@"1000"];
        //********* 陣列的使用 ***********
        // 1、可以向陣列新增元素
        [arr addObject:@"one"];
        [arr addObject:@"one"];
        [arr addObject:@"one"];
        [arr addObject:@"one"];

        // 把另外一個陣列,整體新增到陣列中
        [arr2 addObjectsFromArray:array];

        // 2、計算陣列的長度
        NSUInteger len = arr.count;

        // 3、插入一個元素在指定的位置
        [arr insertObject:@"1" atIndex:2];

        // 4、刪除最後一個元素
        [arr removeLastObject];   //刪除最後一個元素
        [arr removeObject:@"1"];  //刪除指定元素

        // 5、替換元素
        //[arr replaceObjectAtIndex:1 withObject:@"two"];
        arr[1] = @"two";

        // 6、交換元素
        [arr exchangeObjectAtIndex:0 withObjectAtIndex:1];


        //NSMutableArray 錯誤用法
        // NSMutableArray *arr8 = @[@"one",@"two"];
        // [arr8 addObject:@"three"];

        NSLog(@"len = %ld",len);
        NSLog(@"%@",arr);


}

12. NSDictionary的介紹及使用


/**
 *  字典的建立方法
 */
void test(){

    //NSDictionary 字典
    //NSArray     @"1"  @“2”

    //字典的結構
    // 鍵值對
    // key(鍵)   value(實際的值)
    // zs             張三
    // ls             李四

    //建立字典
    //1、使用類方法建立字典
    //   字典初始化後,內部是無序的
    NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"zs",@"lisi",@"ls", nil];

    NSDictionary *dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"zhangsan",@"key1",@"lisi",@"key2", nil];

    NSLog(@"%@",dict2);
    //獲取字典的長度
    NSLog(@"%ld",dict2.count);

    //2、快速建立字典  @{key:value,key1:value1}
    // 在字典中,key值是不能夠重複的,重複的時候不會報錯
    // 重複的只保留一個(第一次出現的那個)
    NSDictionary *dict3 = @{@"zs":@"zhangsan",@"ls":@"lisi",@"zs":@"fengjie"};
    NSLog(@"%@",dict3);

}

/**
 *  NSDictionary 基本使用
 */
void test2(){

    //字典長度 ?
    // 2   -- @"zs":@"fengjie"  沒有被新增到字典中,原因是key值重複了
    NSDictionary *dict3 = @{@"zs":@"zhangsan",@"ls":@"lisi",@"zs":@"fengjie"};
    //1) 獲取字典長度(鍵值對的個數)
    NSLog(@"%ld",dict3.count);
    NSLog(@"%@",dict3);

    //2)根據key獲取 value 只獲取zs
    NSString *s = [dict3 objectForKey:@"zs"];
    NSLog(@"%@",s);


}


-(void)test3(){

         NSArray *arr = @[@"1",@"2"];
         NSDictionary *dict3 = @{@"zs":@"zhangsan",@"ls":@"lisi",@"arr":@"fengjie"};
        //1、關於字典的遍歷問題
        //for(int i=0;i<dict3.count;i++){

            //根據key  --->  value

        //}

        //2、使用增強型for 迴圈可以遍歷
        // str 存放的 key    還是 value
        // 通過這種方式,得到的是字典的key值
        //        for (NSString *str in dict3) {
        //            // 得到的事key
        //            NSString *ss = [dict3 objectForKey:str];
        //            NSLog(@"%@ ---> %@",str,ss);
        //        }

        // 3、使用block 進行遍歷
        // key  就是我們鍵值對 key值
        // obj  就是我們key 對應的 value值

        [dict3 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

            NSLog(@"%@--->%@",key,obj);
        }];

}

13. NSDictionary的簡寫及檔案操作


/**
 *  Dictionary的簡寫形式
 */
void test(){

    //建立字典的簡寫形式
    NSDictionary *dict3 = @{@"zs":@"zhangsan",@"ls":@"lisi",@"arr":@"fengjie"};

    //獲取value值得簡寫形式
    NSLog(@"%@",dict3[@"arr"]);

}


-(void)test2(){

//NSDictionary的檔案操作

        NSArray *arr = @[@"1",@"2",@"one"];

        NSDictionary *dict = @{@"1":@"one",@"2":@"two"};
        //1、把字典的內容寫入到檔案中
        //   writeToFile
        NSDictionary *dict3 = @{@"zs":@"zhangsan",@"dict":dict,@"arr":arr};
        //把字典寫入到檔案中
       BOOL flag = [dict3 writeToFile:@"/Users/apple/Desktop/dict.plist" atomically:YES];
        if (flag) {
            NSLog(@"寫入成功!");
        }

        //2、從檔案中讀取資料,放到字典中
        // 給一個路徑
        NSDictionary *dict4 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/apple/Desktop/dict.plist"];

        //獲取字典中的陣列
        NSArray *arr2 = dict4[@"arr"];
        NSLog(@"%@",arr2);

        //獲取字典中的字典
        NSDictionary *dict5 = dict4[@"dict"];
        NSLog(@"%@",dict5);

}

14.NSMutableDictionary介紹和使用

-(void)test(){

        //建立可變NSMutableDictionary
        // 建立一個空的字典
        NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
        // 使用類方法建立一個字典
        NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2", nil];

        //2、可變字典的常見方法
        //1) 新增元素
        //給他設定值
        //如果新增一個值,實際上是新增一組鍵值對

        [dict1 setObject:@"one" forKey:@"1"];
        [dict1 setObject:@"two" forKey:@"2"];
        [dict1 setObject:@"three" forKey:@"3"];
        [dict1 setObject:@"four" forKey:@"4"];

        //使用dictionary 給字典重新賦值
        dict1.dictionary =@{@"zs":@"zhangsan"};
        dict1[@"1"] = @"one";
        dict1[@"2"] = @"one2";
        dict1[@"3"] = @"one3";
        dict1[@"4"] = @"one4";

        //2) 刪除元素
        [dict1 removeObjectForKey:@"3"];

        //3)  刪除所有元素
        //        [dict1 removeAllObjects];

        NSLog(@"%@",dict1);
}

相關文章