iphone - 查找由字符串分隔的 NSString 内的范围
<p><p>虽然 iOS 提供了很多有用的字符串方法,但我找不到一个好的解决方案来获取由给定字符分隔的字符串范围。</p>
<p><strong>原字符串:</strong> </p>
<blockquote>
<p>|You| will |achieve| everything you |want| if you |work| hard</p>
</blockquote>
<p>分隔符是<code>|</code>。</p>
<p>单独的字符串1:你(范围:3、3)</p>
<p>单独的string2:实现(范围:12、7)</p>
<p>单独的字符串3:想要(范围:37、4)</p>
<p>单独的字符串4:工作(范围:51、4)</p>
<p>NSString 方法的 <code>substringFromIndex:</code> 使得使用 NSString 找到这些范围成为可能,但这似乎效率低下。</p>
<p>请告诉我解决此问题的更好方法。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您应该使用 <a href="https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html" rel="noreferrer noopener nofollow">NSRegularExpression</a>的<a href="https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40009708-CH1-SW6" rel="noreferrer noopener nofollow">matchesInString:options:range:</a>方法。</p>
<blockquote>
<p><strong>Return Value</strong> </p>
<p>An array of <a href="https://developer.apple.com/library/mac/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html" rel="noreferrer noopener nofollow">NSTextCheckingResult</a> objects. Each result
<strong>gives the overall matched range</strong> 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.</p>
</blockquote>
<p>你可能有这样的代码:</p>
<pre><code>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, )];
// ... 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 = ;
NSLog(@"string at range %@ :: \"%@\"",
NSStringFromRange(textResult.range),
substring);
}
}
</code></pre>
<p>日志:</p>
<blockquote>
<p>string at range {1, 3} :: "You"</p>
<p>string at range {5, 6} :: " will "</p>
<p>string at range {12, 7} :: "achieve"</p>
<p>string at range {20, 16} :: " everything you "</p>
<p>string at range {37, 4} :: "want"</p>
<p>string at range {42, 8} :: " if you "</p>
<p>string at range {51, 4} :: "work"</p>
<p>string at range {56, 5} :: " hard"</p>
</blockquote></p>
<p style="font-size: 20px;">关于iphone - 查找由字符串分隔的 NSString 内的范围,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/10385196/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/10385196/
</a>
</p>
页:
[1]