OStack程序员社区-中国程序员成长平台

标题: iphone - 查找由字符串分隔的 NSString 内的范围 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 13:33
标题: iphone - 查找由字符串分隔的 NSString 内的范围

虽然 iOS 提供了很多有用的字符串方法,但我找不到一个好的解决方案来获取由给定字符分隔的字符串范围。

原字符串:

|You| will |achieve| everything you |want| if you |work| hard

分隔符是|

单独的字符串1:你(范围:3、3)

单独的string2:实现(范围:12、7)

单独的字符串3:想要(范围:37、4)

单独的字符串4:工作(范围:51、4)

NSString 方法的 substringFromIndex: 使得使用 NSString 找到这些范围成为可能,但这似乎效率低下。

请告诉我解决此问题的更好方法。



Best Answer-推荐答案


您应该使用 NSRegularExpressionmatchesInStringptions:range:方法。

Return Value

An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

你可能有这样的代码:

NSString *str = @"|You| will |achieve| everything you |want| if you |work| hard";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
    @"[^|]*" options: 0 error:nil];
NSArray *results = [regex matchesInString:str 
                                  options:0 
                                    range:NSMakeRange(0, [str length])];
// ... do interesting code on results...
// Note that you should iterate through the array and use the 'range' property
// to get the range.

for (NSTextCheckingResult *textResult in results)
{
   if (textResult.range.length > 0)
   {
      NSString *substring = [myStr substringWithRange:textResult.range];
      NSLog(@"string at range %@ :: \"%@\"", 
            NSStringFromRange(textResult.range), 
            substring);
   }
}

日志:

string at range {1, 3} :: "You"

string at range {5, 6} :: " will "

string at range {12, 7} :: "achieve"

string at range {20, 16} :: " everything you "

string at range {37, 4} :: "want"

string at range {42, 8} :: " if you "

string at range {51, 4} :: "work"

string at range {56, 5} :: " hard"

关于iphone - 查找由字符串分隔的 NSString 内的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385196/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4