美文网首页
查找字符串位置 给NSString 增加个分类,获取字符串Pat

查找字符串位置 给NSString 增加个分类,获取字符串Pat

作者: Coder大雄 | 来源:发表于2016-09-13 21:08 被阅读117次
    #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;
    }
    

    相关文章

      网友评论

          本文标题:查找字符串位置 给NSString 增加个分类,获取字符串Pat

          本文链接:https://www.haomeiwen.com/subject/syzmettx.html