首页 > 代码库 > 黑马程序员___Foundation__NSString
黑马程序员___Foundation__NSString
NSString
字符串的创建
NSString *s1 = @"jack";
NSString *s2 = [[NSString alloc] initWithString:@"jack"];
NSString *s3 = [[NSString alloc] initWithFormat:@"age is %d", 10];
C字符串 > C字符串
const char *c = [s4 UTF8String];
NSUTF8StringEncoding 用到中文就可以用这种编码
NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];
字符串的导出
NSString *str = @"4234234";
NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/my2.txt"];
[str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
或者
[@"Jack\nJack" writeToFile:@"/Users/apple/Desktop/my.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]
NSMutableString
可变字符串
NSMutableString *s1 = [NSMutableString stringWithFormat:@"my age is 10"];
拼接内容到s1的后面
[s1 appendString:@" 11 12"];
获取is的范围
NSRange range = [s1 rangeOfString:@"is"];
删除is
[s1 deleteCharactersInRange:range];
不可变字符串也可以将两个字符串拼接
NSString *s2 = [NSString stringWithFormat:@"age is 10"];
NSString *s3 = [s2 stringByAppendingString:@" 11 12"];
补充知识:NSURL
file:// 本地资源协议头
http:// 网络资源协议头
创建一个资源路径
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]
黑马程序员___Foundation__NSString