How do I use NSRange with this NSString?

前端 未结 3 415
Happy的楠姐
Happy的楠姐 2021-01-22 02:33

I have the following NSString:

productID = @\"com.sortitapps.themes.pink.book\";

At the end, \"book\" can be anything.... \"music\

相关标签:
3条回答
  • 2021-01-22 02:57

    You can use -[NSString componentsSeparatedByString:@"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:@"."] to join your modified array into a string again.

    0 讨论(0)
  • 2021-01-22 02:59

    You can try a backward search for the dot and use the result to get the desired range:

    NSString *str = @"com.sortitapps.themes.pink.book";
    NSUInteger dot = [str rangeOfString:@"." options:NSBackwardsSearch].location;
    
    NSString *newStr =
       [str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
                                    withString:@"something_else"];
    
    0 讨论(0)
  • 2021-01-22 03:00

    Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:

    [productID stringByDeletingPathExtension];
    

    Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.

    0 讨论(0)
提交回复
热议问题