I believe lastPathComponent
splits based on forward slash "/", your path contains only backslashes "\"
You can try replacing your backslashes:
[path stringByReplacingOccurrencesOfString:@"\\" withString:@"/"].lastPathComponent;
質問
I want to extract the name of a file from a string like this
C:\IBM\...\images\custom\fileName.png
But
[string lastPathComponent];
gives me the whole string instead of fileName.png. What am I doing wrong here?
解決
I believe lastPathComponent
splits based on forward slash "/", your path contains only backslashes "\"
You can try replacing your backslashes:
[path stringByReplacingOccurrencesOfString:@"\\" withString:@"/"].lastPathComponent;
他のヒント
In addition to michaels answer, you could also do the following.
NSArray *listItems = [string componentsSeparatedByString:@"\\"];
NSString *endOfString = [listItems lastObject];
as long as the string is not an empty or nil string, this will work.
And one other alternative to the other fine answers:
NSString *path = @"C:\IBM\...\images\custom\fileName.png";
NSRange backslashRange = [path rangeOfString:@"\\" options:NSBackwardsSearch];
NSString *filename = [path substringFromIndex:backslashRange.location + 1];
Of course this should have proper checking that the string actually has a backslash.
FYI - not that it matters if done on one or just a few strings but this approach is more efficient than the other answers because this approach doesn't needlessly process the whole string or create extra copies.