一、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"];