views:

149

answers:

1

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 results 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!

+5  A: 
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];
Preston
And beaten to the answer again. :)
Brandon Bodnár