[英]How do I use NSRange with this NSString?
I have the following NSString
: 我有以下
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?
我如何使用NSRange执行此操作? Basically I need this:
基本上我需要这个:
partialID = @"com.sortitapps.themes.pink.";
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"];
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. 本质上,我将名称视为文件名,并为此目的使用NSString方法删除最后一个(也是最后一个)扩展名。
您可以使用-[NSString componentsSeparatedByString:@"."]
拆分成组件,使用所需的值创建一个新数组,然后使用[NSArray componentsJoinedByString:@"."]
将修改后的数组再次连接到一个字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.