1.C语言到Object的转换
char *s = "Hello";//OC、C字符窜类型转换//C->OCNSString * str1 = [NSString stringWithUTF8String:s] ;NSLog(@"str1=%@",str1);//OC->CNSLog(@"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);复制代码