jmasterx
jmasterx

Reputation: 54113

Insert string right before last '.' in string

I have this NSString:

@"aa.bb.cc.png"

I want to insert myString right before the .png to make

@"aa.bb.ccSTUFF.png"

Is there a better way to do this than to reverse iterate until '.' is found, then split at location, then add component1 + stuff + extension together?

Thanks

Upvotes: 0

Views: 29

Answers (2)

Rick
Rick

Reputation: 1818

Try this:

NSString *path = [originalPath stringByDeletingPathExtension];
path = [path stringByAppendingString:myString];
path = [path stringByAppendingPathExtension:[originalPath pathExtension]];

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You can use regular expression for that:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
    regularExpressionWithPattern:@"[.]([^.]*)$"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
NSString *res = [regex stringByReplacingMatchesInString:str
    options:0
    range:NSMakeRange(0, [str length])
    withTemplate:@"STUFF.$1"];

The idea behind the regex is to match the last dot and the extension, and then replace with the additional string of your choice ($1 in the replacement template means the content of the first capturing group, which corresponds to the extension).

Upvotes: 1

Related Questions