开发者

How to extract the data I want in NSString?

I开发者_运维百科 have a NSString like this:

456673\tSomething

But I would like to extract Something only.... ... All the data must be in this format ....

xxxx\tyyyy How can I split it bases on \t? thank you.


You may be looking for this instance method:

- (NSArray *)componentsSeparatedByString:(NSString *)separator

If that fails your needs and you want something more powerful, I can personally recommend RegexKitLite. RegexKitLite adds the power of regular expressions to NSString in the form of a category.


I've added a category to NSString for convenience (class: NSString+Utility):

- (NSString *)substringFromFirstOccurenceOfString:(NSString *)string {
    NSRange range = [self rangeOfString:string];

    if (range.location != NSIntegerMax) {
        int index = range.location + range.length;
        return [self substringFromIndex:index];
    } else {
        return self;
    }
}

- (NSString *)substringFromLastOccurenceOfString:(NSString *)string {
    NSRange range = [self rangeOfString:string options:NSBackwardsSearch];

    if (range.location != NSIntegerMax) {
        int index = range.location + range.length;
        return [self substringFromIndex:index];
    } else {
        return self;
    }
}

- (NSString *)substringToFirstOccurenceOfString:(NSString *)string {
    NSRange range = [self rangeOfString:string];    

    if (range.location != NSIntegerMax) {
        int index = range.location + range.length;
        return [self substringToIndex:index];            
    } else {
        return self;
    }
}

- (NSString *)substringToLastOccurenceOfString:(NSString *)string {
    NSRange range = [self rangeOfString:string options:NSBackwardsSearch];  

    if (range.location != NSIntegerMax) {
        int index = range.location;
        return [self substringToIndex:index];       
    } else {
        return self;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜