#import <Foundation/Foundation.h>
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 <Foundation/Foundation.h>
#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;
}
网友评论