Scan from last character instance to end of line using NSScanner

For a line like: "new / path-path / path / 03 - filename.ext", how can I use NSScanner (or any other approach) to return a substring from the last "/" to the end of the line, i.e. "03 - filename.ext"? The code I tried to start 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 leads to a seg error after scanning to the end of the line! I am not sure why this is not working. Ideas? Thanks in advance!

+4
source share
1 answer
 NSString *thePath = @"new/path - path/path/03 - filename.ext"; NSString *lastPathComponent = [thePath lastPathComponent]; // "03 - filename.ext" 

Edit to respond to your request. You do not 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]; 
+11
source

Source: https://habr.com/ru/post/1304628/


All Articles