Foundation框架中的字符串(NSString/NSMutableString)

来源:互联网 发布:冰与火之歌结局 知乎 编辑:程序博客网 时间:2024/05/16 23:39

一、NSString

    1. 字符串的创建

NSString *s1 = @"jack";NSString *s2 = [[NSString alloc] initWithString:@"jack"];NSString *s3 = [[NSString alloc] initWithFormat:@"age is %d", 10];// C字符串转成OC字符串NSString *s4 = [[NSString alloc] initWithUTF8String:"jack"];// OC字符串转成C字符串const char *cs = [s4 UTF8String];


    2. 读取文件中的内容

// 使用文件路径NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];// 使用资源路径NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/1.txt"];NSString *s6 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

资源路径(URL)由两部分组成:协议头+路径,协议头分三种:1. http:// 2. file:// 3. ftp://。

二、NSMutableString

    1. 可变字符串的创建

NSMutableString *s1 = [NSMutableString stringWithFormat:@"age is 10"];

    2. 在字符串s1后面再拼接另一个字符串

[s1 appendString:@" 11 12"];

 

0 0
原创粉丝点击