0

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

2 Answers 2

2

Try this:

NSString *path = [originalPath stringByDeletingPathExtension];
path = [path stringByAppendingString:myString];
path = [path stringByAppendingPathExtension:[originalPath pathExtension]];
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

@Milo If you create the expression upfront, the amortized calls of stringByReplacingMatchesInString method by themselves would probably be less expensive than two appends, because each call does not create a throw-away object in between the two invocations. In the end, the difference in performance would likely not matter at all, so it's going to be a matter of personal preferences.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.