开发者

Scan from last instance of character to end of string using NSScanner

Given a string such as: "new/path - path/path/03 - filename.ext", how can I use NSScanner (or any other approach) to return the substring from the last "/" to the end of the string, i.e., "03 - filename.ext"? The code I've been trying to start with is:

while ([fileScanner isAtEnd] == NO){
    slashPresent = [fileScanner scanUpToString:@"/" intoString:NULL];
    if (slashPresent == YES) {
        [fileScanner scanString:@"/" intoString:NULL];
        lastPosition = [fileScanner scanLocation];
    }
    NSLog(@"fileScanner position: %d", [fileScanner scanLocation]);
    NSLog(@"lastPosition: %d", lastPosition);       
}

...and this res开发者_如何学编程ults in a seg fault after scanning to the end of the string! I'm not sure why this isn't working. Ideas? Thanks in advance!


NSString *thePath = @"new/path - path/path/03 - filename.ext";
NSString *lastPathComponent = [thePath lastPathComponent]; // "03 - filename.ext"

Edit to respond to your followup. You don't need NSScanner:

NSString *thePath = @"new/path - path/path/03 - filename.ext";
NSRange theRange = [thePath rangeOfString:@"/" options:NSBackwardsSearch];
NSString *lastPathComponent = nil;
if (theRange.location != NSNotFound)
    lastPathComponent = [thePath substringFromIndex:theRange.location];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜