天天看点

NSString和NSMutableString的相关总结

自己也是初学,菜鸟一枚,根据老师的课程总结模板,自己记录保存下来,方便以后查阅,有学习的朋友一起分享一下!

1.//OC,C字符串类型转换

Char *s = “Hello Objective-C”;

NSString *str = @”Hello”;

//C->OC

NSString  *str1 = [NSString   stringWithUTF8String : s];

NSLog(@”str1 = %@”, str1);//运行结果:str1 = Hello Objective-C

//0C-C

NSLog(@”str2 = %s”,[str UTF8String]);//运行结果:str2 = Hello

2.//创建字符串

NSString *str3 = @”IOS”;

NSString *str4 = [[NSString alloc] init];

Str4 = @”IOS”;

3./

NSString *str20 = [str18  stringByReplacingOccurrencesOfString:@”Hello” 

withString:@”你好”];

NSLog(@”str20 = %@”, str20);//运行结果:你好 IOS,你好,imooc

11.//读取文件

//文件来源:1.本地文件 2.网络文件

//路径类

NSString *str21 = @”www.baidu.com”;

//网络路径

NSURL *httpURL = [NSURL   URLWithString:str21];

//本地路径

NSString *fileURL = [NSURL   fileURLWithPath:str21];

//读取网络文件

NSString *httpStr = [NSString   stringWithContentsOfURL:httpURL

encoding: NSUTF8StringEncoding error :nil];

NSLog(@”httpStr = %@”, httpStr);

//读取本地文件:创建文件-文本编辑-格式-制作纯文本,假设在桌面中创建了test.txt文件

//test.txt中可写入内容: Hello IOS, Hello imooc;

NSString *fileStr = [NSString  stringWithContentsOfFile:@”/Users/Visitor/Desktop/test.txt”encoding:NSUTF8StringEncoding error: nil];

NSLog(@fileStr = “%@”,fileStr);//运行结果:fileStr = Hello IOS,Helloimooc;

12.//写入文件

NSString *str22 = @”Hello Visitor”;

BOOL isOk=[Str22   writeToFile:@”/Users/Visitor/Desktop/test.txt”

atomically:YESencoding:NSUTF8StringEncoding error: nil];

If(isOk)

  NSLog(@”文件写入成功”);

Else

  NSLog(@”文件写入失败”);//运行结果:文件写入成功

NSMutableString可变字符串

NSMutableString *str =[ [NSMutableString alloc]initWithCapacity:10];

[str setString:@”Hello”];//先分配10个字节内存,然后超出后自动增加,因为这是动态可变

1.//追加字符串

[str appendString:@” world”];

NSLog(@”str = %@”, str);//运行结果:str = Hello world

int a = 10;

[str appendFormat:@” - %d ”,a];

NSLog(@”str = %@”, str);//运行结果 str = Hello world - 10

2.//替换字符串

NSRange range = [str   rangeOfString:@”world”];

[str replaceCharactersInRange:rangewithString:@”IOS”];

NSLog(@”str = %@”, str);//运行结果:str = Hello IOS - 10

3.//插入字符串

[Str insertString:@”A” atIndex:6];

NSLog(@”str = %@”,str);//运行结果:str = Hello AIOS - 10

4.//删除字符串

NSRange range1 = [str rangeOfString:@”AIOS”];

[str deleteCharactersInRange:range1];

NSLog(@”str = %@”, str);//运行结果: str = Hello -10