[oc學習筆記]字串,oc學習筆記字串
1 //建立字串 2 NSString *str1 = [NSString string]; 3 //建立c字串 4 NSString *str2 = [NSString stringWithCString:"ss" encoding:NSUTF8StringEncoding]; 5 //用字串建立字串 6 NSString *str3 = [NSString stringWithString:@"dd"]; 7 //建立nslog()格式的字串 8 NSString *str4 = [NSString stringWithFormat:@"s"]; 9 //將檔案內容設定為字串內容 10 NSString *path = @"/Users/XuLee/Desktop/oc/abc.txt";//檔案路徑 11 NSError *error;//錯誤資訊 12 NSString *ss = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 13 if (error) { 14 NSLog(@"%@",error);//列印錯誤資訊 15 } 16 //將字串寫入檔案 17 [ss writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]; 18 //列印錯誤資訊 19 if (error) { 20 NSLog(@"%@",error); 21 } 22 23 //字串的初始化 24 NSString *str5 = [[NSString alloc]init]; 25 //字串來初始化字串 26 NSString *str6 = [[NSString alloc]initWithString:@"jj"]; 27 //用c字串初始化字串 28 NSString *str7 = [[NSString alloc]initWithCString:"s" encoding:NSUTF8StringEncoding]; 29 //用nslog初始化字串 30 NSString *str8 = [[NSString alloc]initWithFormat:@"s"]; 31 //將檔案內容設定為字串的初始化 32 NSString *sss = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 33 if (error) { 34 NSLog(@"%@",error);//列印錯誤資訊 35 } 36 37 38 //字串的判斷和比較 39 //判斷字串是否以某某字元開始 傳回值 0 或者 1 40 NSLog(@"%zi",[ss hasPrefix:@"ss"]); 41 //判斷字串是否以某某字元結尾 傳回值0 或者1 42 NSLog(@"%zi",[ss hasSuffix:@"s"]); 43 //比較字串的大小 傳回值 0 1 -1 44 [ss compare:sss];//如果ss>sss則返回1 ss=sss返回0 ss<sss返回-1 45 //傳回值類型為NSComparisonResult 46 //判斷是否存在某某字串 傳回值 0 或者 1 47 [ss containsString:@"d"]; 48 49 50 51 //字串的大小寫轉換 產生新的字串 52 //轉化為大寫 53 [ss uppercaseString]; 54 //轉化為小寫 55 [ss lowercaseString]; 56 //除了首字母大寫 其餘全部小寫 57 [ss capitalizedString]; 58 59 //字串的剪下 產生新的字串 60 //剪下到從制定位置剪下到最後,包括指定位置 61 [ss substringFromIndex:2]; 62 //從開始開始剪下到指定位置,不包括指定位置 63 [ss substringToIndex:2]; 64 //剪下指定範圍內的內容 65 [ss substringWithRange:NSMakeRange(1, 2)]; 66 67 68 //類型轉化 產生相應類型 但必須字串內容符合相應內容 69 //整形 70 [ss intValue]; 71 //浮點型 72 [ss floatValue]; 73 [ss doubleValue]; 74 75 76 //其他 77 //將c字串轉化為oc字串 78 char s[3] = "s"; 79 NSString *oc = @(s); 80 //字串中某個位置的字元 81 unichar c = [ss characterAtIndex:2]; 82 //字串長度 83 NSLog(@"%zi",ss.length); 84 //在字串後面加一個字串 產生一個新的字串 85 [ss stringByAppendingString:@"ss"]; 86 //尋找是否存在某某字元 傳回值為一個範圍 87 [ss rangeOfString:@"ss"]; 88 //如果沒找到 range.location = nsnotfound 89 //後面替換前面 90 [ss stringByReplacingOccurrencesOfString:@"ss" withString:@"sss"]; 91 92 93 //可變字串 94 //建立 一定要先給他空間 在進行賦值 95 NSMutableString *nss = [[NSMutableString alloc]initWithCapacity:10]; 96 NSMutableString *nss2 = [NSMutableString stringWithCapacity:10]; 97 //賦值 98 //在末尾加一個字串 99 [nss appendString:@"s"];100 //加一個初始化了的字串101 [nss appendFormat:@"sss%@",ss];102 //在指定位置插入內容103 [nss insertString:@"s" atIndex:2];104 //刪除制定範圍內的字串105 [nss deleteCharactersInRange:NSMakeRange(1, 2)];106 //使用字串代替制定範圍內的內容107 [nss replaceCharactersInRange:NSMakeRange(1, 2) withString:@"sss"];