#字符串学习总结
##1. 创建
//构造方法
NSString *s1 = [[NSString alloc] initWithFormat:@"%@ 真简单", @"iOS开发"];
//类方法
NSString *s2 = [NSString stringWithFormat:@"%@ 好简单啊", @"OC"];
// 将 C 语言字符串转换成 OC 字符串
NSString *s3 = [[NSString alloc] initWithUTF8String:"hello iOS"];
//从文件读取
NSString *file = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Launchable.h" encoding:NSUTF8StringEncoding error:nil];
//从url读取
NSString *html = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.youdao.com"] encoding:NSUTF8StringEncoding error:nil];
##2. 查看
//1. 比较
BOOL isEqual = [@”123” isEqualToString:@”123”];
//下面这个方法可以根据options进行排序,常见的有按数字排序(options:NSNumericSearch),
//有按照字符串排序, 还可以根据正则表达式排序
NSComparisonResult result = [@”123” compare:@”124” options:NSNumericSearch]);
//2. 判断字符串的前后缀, 返回值均为bool类型
[@"123.txt" hasSuffix:@".txt"]
[@"http://www.baidu.com hasPrefix:@"http://"]
//3. 根据range取字符串
//3.1 从字符串中获得子字符串的range
NSRange range = [@"abcdefgcdefg"; rangeOfString:@"acd"];
//可以通过判断range.location 判断有没有找到
if(range.location == NSNotFound) {
NSLog(@"没有找到");
}
//3.2下面是一个例子寻找字符串中所有包含子字符串的位置和长度,
str = @"123abcd456defg123ab45qw";
NSRange range = NSMakeRange(0, 0);
do {
NSUInteger loc = range.location + range.length;
NSUInteger len = str.length - loc;
range = [str rangeOfString:@"3a" options:1 range:NSMakeRange(loc, len)];
if (range.location != NSNotFound) {
NSLog(@"%@", NSStringFromRange(range));
}
} while (range.location != NSNotFound);
//4. 获取子字符串
// 子字符串 substring
NSString *str = @"0123456789";
NSString *s1 = [str substringFromIndex:5];
NSLog(@"%@", s1);
NSString *s2 = [str substringToIndex:5];
NSLog(@"%@", s2);
// 在科学计算中有一个习惯, 表示范围的时候, 左边取得到, 右边取不到
// arc4random_uniform(10)
// 左闭右开区间
NSRange range = NSMakeRange(3, 3);
NSString *s3 = [str substringWithRange:range];
NSLog(@"%@", s3);
//5. 通过正则匹配字符串
// 正则表达式, regular expression
// [^字符] 含义是非该字符的字符
// [^<] 不是 < 的任意字符
// + 放在通配符的后面, 表示多个的意思
// [^<]+ 就是任意多个不由<组合而来的字符串
NSString *mark = @"<sapn style\"color:red\">1234567890987654321qazwsxedc</span>";
NSRange range = [mark rangeOfString:@">[^<]+<" options:1024];
range = NSMakeRange(range.location + 1, range.length - 2);
NSString *res = [mark substringWithRange:range];
NSLog(@"%@", res);
//6. 其他用法
//去掉首尾空格
NSString *str1 = @" admin ";
NSLog(@"|%@|", str1);
str1 = [str1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"|%@|", str1);
//去掉收尾大写
NSString *str2 = @"ABCadminDEF";
NSLog(@"|%@|", str2);
str2 = [str2 stringByTrimmingCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet]];
NSLog(@"|%@|", str2);
去掉首尾小写
NSString *str3 = @"abcADMINdefg";
NSLog(@"|%@|", str3);
str3 = [str3 stringByTrimmingCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
NSLog(@"|%@|", str3);
//去掉/
NSString *path = @"/Users/apple/Destop/";
path = [path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
NSLog(@"path = %@", path);