如何获取NSString的子字符串? [英] How to get substring of NSString?
本文介绍了如何获取NSString的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想从NSString @值获取值:hello World:value
,我应该使用什么?
If I want to get a value from the NSString @"value:hello World:value"
, what should I use?
我想要的返回值是 @hello World
。
推荐答案
选项1:
NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"
选项2: b
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];
这可能是一个有点超过顶部你的相当微不足道的情况。
This one might be a bit over the top for your rather trivial case though.
选项3:
NSString *needle = [haystack componentsSeparatedByString:@":"][1];
这会在分割时创建三个临时字符串和数组。
This one creates three temporary strings and an array while splitting.
所有代码段假定搜索的内容实际上包含在字符串中。
All snippets assume that what's searched for is actually contained in the string.
这篇关于如何获取NSString的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文