NSString的几个方法(rangeOfString,hasPrefix,hasSuffix,改变大小写...)

时间:2022-02-14 08:12:02

- (NSRange)rangeOfString:(NSString *)searchString;//查找字符串中是包涵在某个字符串,并返回其开始位置和长度

例:

NSRange range = [link rangeOfString:@"target=_blank"];

if(range.location != NSNotFound)

{

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:link]];

}
-(BOOL) hasPrefix:(NSString *) //astring;检查字符串是否以astring开头; 
-(BOOL) hasSuffix:(NSString *) //astring;检查字符串是否以astring结尾;
1.) lowercaseString: 将字符串转换为小写
2.) uppercaseString: 将字符串转换为大写
3.) capitalizedString:将字符串的首字母大写
忽略大小写比较
//忽略大小写进行比较,返回值与compare一样
result = [str1 caseInsensitiveCompare:str2];
if (result == NSOrderedAscending) {
NSLog(@"右边 > 左边");
}else if(result == NSOrderedSame){
NSLog(@"内容相同");
}else if (result == NSOrderedDescending){
NSLog(@"左边 > 右边");
}
//拓展名
//获取拓展名,不带.
NSString *str2 = @"Users/CentralPerk/Desktop/test.txt";
NSLog(@"%@",[str2 pathExtension]);
//添加拓展名,不需要带.
NSLog(@"%@",[str2 stringByAppendingPathExtension:@"mp3"]);
//删除拓展名,带.一块删除
NSLog(@"%@",[str2 stringByDeletingPathExtension]);
        //字符串的截取
NSString *str = @"";
NSLog(@"%@",[str substringFromIndex:]);
NSLog(@"%@",[str substringToIndex:]);
NSLog(@"%@",[str substringWithRange:NSMakeRange(, )]); //用指定字符串分割字符串,返回一个数组
NSArray *array = [@"1,2,3,4,5,6" componentsSeparatedByString:@","];
NSLog(@"%@",array); //将数组中的字符串组合成一个文件路径
NSMutableArray *components = [NSMutableArray array];
[components addObject:@"Users"];
[components addObject:@"CentralPerk"];
[components addObject:@"Desktop"];
NSString *path = [NSString pathWithComponents:components];
NSLog(@"%@",path); //Users/CentralPerk/Desktop //将一个路径分割成一个数组
NSArray *array1 = [path pathComponents];
NSLog(@"%@",array1); //判断是否为绝对路径(依据:是否以'/'开始)
path = @"/Users/CentralPerk/Desktop";
NSLog(@"%i",[path isAbsolutePath]); //获取最后一个目录
NSLog(@"%@",[path lastPathComponent]); //删除最后一个目录
NSLog(@"%@",[path stringByDeletingLastPathComponent]); //拼接一个目录
NSLog(@"%@",[path stringByAppendingPathComponent:@"aaa"]); ///Users/CentralPerk/Desktop/aaa
NSLog(@"%@",[path stringByAppendingString:@"aaa"]); ///Users/CentralPerk/Desktopaaa
NSLog(@"%@",[path stringByAppendingFormat:@"%@%@",@"b",@"c"]); ///Users/CentralPerk/Desktopbc

查看字符串中是否包含某个字符串

NSString *str1 = @"abcd";

NSString *str = @"a";

//在str1这个字符串中搜索\n,判断有没有

if ([str1 rangeOfString:str].location != NSNotFound) {

NSLog(@"这个字符串中有a");

 }

 //rangeOfString 前面的参数是要被搜索的字符串,后面的是要搜索的字符

//NSNotFound 表示请求操作的某个内容或者item没有发现,或者不存在

截取字符串到指定字符

NSString *string = @"abcdefghijklmn";
NSRange range = [string rangeOfString:@"h"];
string = [string substringToIndex:range.location];
NSLog(@"string:%@",string);