查找字符串位置 给NSString 增加个分类,获取字符串Patience is bitter, but its fruit is sweet.中bitter开始下标与结束下标的位置(字符串:)

#import 

struct Location {
    //开始下标
    NSUInteger begin;
    //结束下标
    NSUInteger end;
};
typedef struct Location Location;

@interface NSString (Location)

- (Location)rangeOfSubString:(NSString *)str;

@end
#import "NSString+Location.h"

@implementation NSString (Location)

- (Location)rangeOfSubString:(NSString *)str {
    //获取字符串的范围
    NSRange range = [self rangeOfString:str];
    Location location = {range.location, (range.location + range.length -1)};
    return location;
}
@end
#import 
#import "NSString+Location.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSString *str = @"Patience is bitter, but its fruit is sweet.";
        
        Location location = [str rangeOfSubString:@"bitter"];
        //输出开始下标 和结束下标
        NSLog(@"begin = %lu, end = %lu", location.begin, location.end);
        
        
    }
    return 0;
}

你可能感兴趣的:(查找字符串位置 给NSString 增加个分类,获取字符串Patience is bitter, but its fruit is sweet.中bitter开始下标与结束下标的位置(字符串:))