Foundation框架系列-NSString

NSString

OC字符串与C语言字符串转换

NSString *str = @"Hello world ! !";
// OC字符串 --> C语言字符串
char *c = [str UTF8String]; // C字符串 --> OC语言字符串
char *c = "Hello world ! !";
NSString *str = [[NSString alloc] initWithUTF8String:c];

从文件中读取字符串

// 文件的绝对路径
NSString *str1 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/abc.txt" encoding:NSUTF8StringEncoding error:nil]; // 资源
NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/abc.txt"];
NSString *str2 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

获取字符串中指定内容的NSRange

NSString *str = @"Hello world";
// 获取字符串
NSRange range = [str rangeOfString:@"Hello"];

字符串的截取

NSString *str = @"HelloWorld";

// 指定index开始截取字符串(包含index)
NSString *str2 = [str substringFromIndex:2]; // 从字符串开始位置开始截取到index(不包含index)
NSString *str2 = [str substringToIndex:3]; // 从index开始包含index截取长度为length的字符串
NSString *str2 = [str substringWithRange:NSMakeRange(2, 2)]; // 从字符串中截取已知字符后面的全部内容
NSString *str = @"wechat://router";
NSRange chemeRange = [str rangeOfString: @"wechat://"];
NSString *str2 = [str substringFromIndex:chemeRange.location + chemeRange.length];
NSLog(@"\nstr2 = %@", str2); // 输出结果: router
上一篇:Foundation框架系列-NSArray


下一篇:模板方法模式(Template Method Pattern)