0

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:@""];
Community
  • 1
  • 1
Johnny Rockex
  • 4,136
  • 3
  • 35
  • 55

2 Answers2

2

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];
John Parker
  • 54,048
  • 11
  • 129
  • 129
0

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

Mario
  • 35,726
  • 5
  • 62
  • 78