How do I use NSRange with this NSString?

落花浮王杯 提交于 2019-12-02 06:12:39

问题


I have the following NSString:

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

At the end, "book" can be anything.... "music", "movies", "games", etc.

I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:

partialID = @"com.sortitapps.themes.pink.";

回答1:


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"];



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9726806/how-do-i-use-nsrange-with-this-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!