黑马程序员---Foundation常用类之NSString/NSMutableString

来源:互联网 发布:人民币汇率月度数据 编辑:程序博客网 时间:2024/05/07 08:01

———Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ———

常用的类有:

NSString/NSMutableString,NSArray/NSMutableArray,NSSet/NSMutableSet,NSDictionary/NSMutableDictionary,NSDate,NSObject
其中NSArray/NSMutableArray,NSSet/NSMutableSet,NSDictionary/NSMutableDictionary,称为集合类
一:NSString/NSMutableString
NSString:不可变字符串    NSMutableString : 可变字符串
字符串创建的几种方法
  1->   NSString *s1 = @"jack";
  2->   NSString *s2 = [[NSString alloc] initWithFormat:@"age is %d",10];
           NSString *s3 = [[NSString alloc] initWithString:@"jack"];
  3->   NSString *s4 = [[NSString alloc] initWithUTF8String:"jack"]; // 将c字符串转为OC字符串
  4->      const  char *cs = [s4 UTF8String]; // 将oc字符串转为C字符串
  5->从文件中读取字符串
先读取文件,再把文件转为字符串
读取文件:第一种方式: 
NSString *str=[NSString alloc] initWithContentsOfFile:<#(NSString *)#> encoding:<#(NSStringEncoding)#>error:<#(NSError *__autoreleasing *)#>
第一处参数传的是文件的绝对路径,以/开头的,第二处传的是编码,注:如果遇到中文,则使用NSUTF8StringEncoding进行编码,第三处参数是指向指针的指针
<span style="font-size:14px;"> NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil]; NSLog(@"\n%@",s5); //就可读取出1.txt的文件内容</span>
可以检测代码量。
6->读取文件:第二种方式:
<span style="font-size:14px;">NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/1.txt"];NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/1.txt"]; //这个方法是知道了协议头,所以只传路径就可NSString *s6 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];NSLog(@"s6=\n%@", s6);    </span>
7->一般都会有一个类方法跟对象方法配对

     [NSURL URLWithString:<#(NSString *)#>];

     [NSString stringWithFormat:@""];

     [NSString stringWithContentsOfFile:<#(NSString *)#> encoding:<#(NSStringEncoding)#> error:<#(NSError *__autoreleasing *)#>];

URL :资源路径

 协议头://路径 

 本地资源   file:// 

 网络资源  http://

ftp://

  http://weibo.com/a.png //网上的一个图片资源

把字符串写入文件中

一种方式:

[@"Jack\nJack"writeToFile:@"/Users/apple/Desktop/my.txt"atomically:YESencoding:NSUTF8StringEncodingerror:nil];

//文件中的换行都是用\n. 

//写Yes代表原则性操作,如果中途写入失败的话,那么这个文件就不会创建, 写NO代表非原则性操作,如果中途写入失败,那么文件还会创建 

另一种方式:

<span style="font-size:14px;"> NSString *str = @"4234234";    NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/my2.txt"];    [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];</span>
NSMutableString : 可变字符串
NSMutableString 的创建方式:

<span style="font-size:14px;">NSMutableString *s1 = [NSMutableString stringWithFormat:@"my age is 10"];    // 拼接内容到s1的后面    [s1 appendString:@" 11 12"];        // 获取is的范围    NSRange range = [s1 rangeOfString:@"is"];    [s1 deleteCharactersInRange:range];// 这两个方法经常一起使用,先找到某个固定字符串的位置,然后在删除        NSString *s2 = [NSString stringWithFormat:@"age is 10"];    NSString *s3 = [s2 stringByAppendingString:@" 11 12"]; // 调用这个方法后,先把s2拷贝出来,把拼接的拼上之后成为一个新的字符串,原来的s2是不变的    NSLog(@"s1=%@, s2=%@", s1, s2);</span>

0 0
原创粉丝点击