NSString: changing a filename but not the extension
Times like this and my Objective-C noobness shows. :-/
So, the more I work on a routine to do this, the more complex it's becoming, and I'm wondering if there isn't just a simple method to change the name of a filename in a path. Basica开发者_运维百科lly, I want to change @"/some/path/abc.txt
to @"/some/path/xyz.txt
-- replacing the filename portion but not changing the path or extension.
Thanks!
Try the following:
NSString* initPath = ...
NSString *newPath = [[NSString stringWithFormat:@"%@/%@",
[initPath stringByDeletingLastPathComponent], newFileName]
stringByAppendingPathExtension:[initPath pathExtension]];
What Vladimir said, just broken down more to make it a little easier to read:
NSString *pathToFile = @"/Path/To/File.txt";
NSString *oldFileName = [pathToFile lastPathComponent];
NSString *newFileName = [@"Document" stringByAppendingPathExtension:[oldFileName pathExtension];
NSString *newPathToFile = [pathToFile stringByDeletingLastPathComponent];
[newPathToFile stringByAppendingString:newFileName];
Take a look at the "Working With Paths" section of the NSString docs. In particular, lastPathComponent
, pathExtension
and stringByDeletingPathExtension:
should do what you want.
You can try something like this:
NSRange slashRange = [myString rangeOfString:@"\\" options:NSBackwardsSearch];
NSRange periodRange = [myString rangeOfString:@"." options:NSBackwardsSearch];
NSString *newString = [myString stringByReplacingCharactersInRange:NSMakeRange(slashRange.location, periodRange.location) withString:@"replacement-string-here"];
What this code does is it gets the location of the \
and .
characters and performs a backwards search so that it returns the last occurrence of it in the string.
Then, it creates a new range based on those previous ranges and replaces the contents in that range with stringByReplacingCharactersInRange:
.
Try this:
NSString* path = [startString stringByDeletingLastPathComponent];
NSString* extension = [startString pathExtension];
NSString* replacementFileName = [@"foo" stringByAppendingPathExtension: extension];
NSString result = [path stringByAppendingPathComponent: replacementFileName];
精彩评论