Tim Sullivan
Tim Sullivan

Reputation: 16888

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. Basically, 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!

Upvotes: 2

Views: 4487

Answers (5)

peelman
peelman

Reputation: 1349

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];

Upvotes: 4

JeremyP
JeremyP

Reputation: 86651

Try this:

NSString* path = [startString stringByDeletingLastPathComponent];
NSString* extension = [startString pathExtension];
NSString* replacementFileName = [@"foo" stringByAppendingPathExtension: extension];
NSString result = [path stringByAppendingPathComponent: replacementFileName];

Upvotes: 1

Vladimir
Vladimir

Reputation: 170839

Try the following:

NSString* initPath = ...
NSString *newPath = [[NSString stringWithFormat:@"%@/%@",
                    [initPath stringByDeletingLastPathComponent], newFileName] 
                     stringByAppendingPathExtension:[initPath pathExtension]];

Upvotes: 6

Chuck
Chuck

Reputation: 237060

Take a look at the "Working With Paths" section of the NSString docs. In particular, lastPathComponent, pathExtension and stringByDeletingPathExtension: should do what you want.

Upvotes: 3

Jacob Relkin
Jacob Relkin

Reputation: 163248

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:.

Upvotes: 2

Related Questions