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];
精彩评论