Johnny Rockex
Johnny Rockex

Reputation: 4196

More efficient way of stringByReplacingOccurrencesOfString

Is there a more efficient way of stripping a string of undesirable phrases, in this case image extensions? I understand that it's possible to use NSCharacterSet as used here: Replace multiple characters in a string in Objective-C? but for whole phrases?

    NSString *title = [imagePath lastPathComponent];
    title = [title stringByReplacingOccurrencesOfString:@".JPG" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@".JPEG" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@".PNG" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@".jpg" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@".jpeg" withString:@""];
    title = [title stringByReplacingOccurrencesOfString:@".png" withString:@""];

Upvotes: 0

Views: 254

Answers (2)

Manoj Udupa
Manoj Udupa

Reputation: 60

There's a method in NSString called -stringByDeletingPathExtension which can be used to delete the extension as follows:

NSString *title = [imagePath lastPathComponent];
NSString *titleMinusExtension = [title stringByDeletingPathExtension];

Upvotes: 2

Mario
Mario

Reputation: 36487

Assuming that you're always having some given image file names, nothing some user can input in a text box, I'd simply use the filename and always strip the last . with everything following.

So in short (no code as I don't know Objective C, which you should add as a tag):

  • Find the last . in the string.
  • Strip everything beginning with the found position.

This way you should always end up with a clean file name and you won't have to do multiple lookups and you won't have to worry about modifying some other part of the file name (let's just assume there's another .jpeg somewhere in there).

Upvotes: 0

Related Questions