字符串NSRange的使用

//
//  main.m
//  OC语言学习


#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /*
         NSString类(和其他Foundation类)的一些方法中,使用了特殊的数据类型NSRange创建范围对象。实际上,它是结构的typedef定义,包含 location 和 length 两个成员
         */
       
        NSString *str1 = @"this is string A";
        NSString *str2 = @"this is string B";
        NSString *res;
        NSRange subRange;
        
        //从字符串中提取前3个字符
        res = [str1 substringToIndex:3];
        NSLog(@"%@",res); //thi
        
        //提取从索引5开始直到结尾的字符串
        res = [str1 substringFromIndex:5];
        NSLog(@"%@",res); //is string A
        
        //提取从索引8开始后的6个字符
        res = [str1 substringWithRange:NSMakeRange(8, 6)];
        NSLog(@"%@",res); //string
        
        //从另一个字符串中查找一个字符串
        subRange = [str1 rangeOfString:@"string A"];
        NSLog(@"index=%lu,length=%lu",subRange.location,subRange.length); //index=8,length=8
        
        subRange = [str1 rangeOfString:@"string B"];
        if (subRange.location == NSNotFound) {
            NSLog(@"没有找到");
        }
    }
    return 0;
}