IOS筆記之字串

翻身不做鹹魚發表於2018-07-15
1.C語言到Object的轉換
char *s = "Hello";
//OC、C字元竄型別轉換
//C->OC
NSString * str1 = [NSString stringWithUTF8String:s] ;
NSLog(@"str1=%@",str1);
//OC->C
NSLog(@"str2 = %s",[str1 UTF8String]);
複製程式碼
2.建立字串
NSString *str3 = @"ios";
NSString *str4 =[[NSString alloc] init]; //需要手動釋放記憶體
str4 = @"IOS";
複製程式碼
3.格式化字串
int a = 10;
int b =20;
NSString *str5 =[NSString stringWithFormat:@"a= %d,b=%d",a,b];
NSLog(@"str5=%@",str5);
複製程式碼
4.拼接字串
NSString *str6 = [str5 stringByAppendingString:str1];
NSLog(@"str6= %@",str6);
複製程式碼
5.大小寫轉換
//轉化小寫
NSString *str7 = @"ABCDEF";
NSString *str8 = [str7 lowercaseString];
NSLog(@"str8 = %@",str8);

//轉化大寫
NSString *str9 = [str7 uppercaseString];
NSLog(@"str9=%@",str9);
複製程式碼
6.字首和字尾的判斷
//判斷字首
NSString *str10 = @"www.imooc.com";
BOOL hasPreFix = [str10 hasPrefix:@"www."];
if(hasPreFix){
    NSLog(@"有對應字首");
}else{
    NSLog(@"沒有對應字首");
}

//判斷字尾
BOOL hasSuffix = [str10 hasSuffix:@".com"];
if(hasSuffix){
    NSLog(@"有對應字尾");
}else{
    NSLog(@"有對應字尾");
}
複製程式碼
7.判斷兩個字元竄是否相同
NSString *str11 = @"hello world";
NSString *str12 = @"hello";
if([str11 isEqualToString:str12]){
    NSLog(@"兩個字元竄一致");
}else{
    NSLog(@"兩個字元竄不一致");
}
複製程式碼
8.分割字串
//按照指定字元分割字串
NSString *str13 = @"a,b,c,d,e,f,g";
NSArray *strArray = [str13 componentsSeparatedByString:@","];
for (NSString *s in strArray) {
    NSLog(@"s =%@",s);
}

//按照範圍擷取字串
NSRange range = NSMakeRange(1, 5); //包含頭尾
NSString *str14 = [str13 substringWithRange:range];
NSLog(@"str14= %@",str14);

//從某一位開始擷取後面字串
NSString *str15 = [str13 substringFromIndex:2];
NSLog(@"str15 = %@",str15);

//從開頭擷取到某一位
NSString *str16 = [str13 substringToIndex:7];
NSLog(@"str16 =%@",str16);

//將字串拆分為每一個字元
for (int i =0; i < str13.length; i++) {
    NSLog(@"%c",[str13 characterAtIndex:i]);
}

複製程式碼
9.查詢字元竄
NSString *str17 = @"ab cd ef gh ij ab";
NSRange range1 = [str17 rangeOfString:@"ab"];
NSLog(@"location:%ld,length:%ld",range1.location,range1.length);
複製程式碼
10.替換字串
//用指定字串替換原字元竄
NSString *str20 = [str18 
stringByReplacingOccurrencesOfString:@"Hello" withString:@"你好"];
NSLog(@"str20 =%@",str20);
複製程式碼
11.獲取檔案
檔案來源:1.本地檔案。2.網路檔案

本地檔案讀取:
NSString *fileStr = [NSString stringWithContentsOfFile:@"/Users/xxx/Desktop/test.txt" encoding:NSUTF8StringEncoding error:nil];
NSLog(@"fileStr =%@",fileStr);

本地檔案寫入:
NSString *str22 = @"hello wuxuanyi";
BOOL isOK = [str22 writeToFile:@"/Users/xxx/Desktop/wuxuanyi.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
if(isOK){
    NSLog(@"寫入檔案成功");
}else{
    NSLog(@"寫入檔案失敗");
}

網路檔案讀取:
NSURL *httpURL = [NSURL URLWithString:str21]; //網路路徑
NSString *httpStr = [NSString 
stringWithContentsOfURL:httpURL encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"httpStr= %@",httpStr);
複製程式碼

相關文章