ios - 检查字符串是否包含数组中的任何字符串
<p><p>我知道我可以检查一个字符串是否包含另一个像这样的字符串</p>
<pre><code>NSString *string = @"hello bla bla";
if (.location == NSNotFound) {
NSLog(@"string does not contain bla");
} else {
NSLog(@"string contains bla!");
}
</code></pre>
<p>但是如果我有一个 <code>NSArray *arary = @[@"one",@"two", @"three", @"four"]</code> 并且我想检查一个字符串包含其中之一而不只是循环或有一堆或 (<code>||</code> )。所以它会是这样的</p>
<pre><code>if (array contains one or two or three or four) {
//do something
}
</code></pre>
<p>但是如果我有一个更长的数组,这会变得乏味,那么有没有另一种方法,而不只是循环?</p>
<p><strong>编辑</strong></p>
<p>我想检查 myArray 是否在 valuesArray 中有任何这些值</p>
<pre><code>valuesArray =@[@"one",@"two", @"three", @"four"];
myArray = [@"I have one head", @"I have two feet", @"I have five fingers"]
</code></pre>
<p>输出</p>
<pre><code>outputArray = @[@"I have one head", @"I have two feet"]
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你去吧:</p>
<pre><code>NSArray* arrRet = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id__nonnull evaluatedObject, NSDictionary<NSString *,id> * __nullable bindings) {
for(NSString* val in valuesArray) {
if (.location != NSNotFound)
return true;
}
return false;
}]];
</code></pre>
<p><code>arrRet</code> 恰好包含两个所需的字符串。</p>
<p>更神奇的一点是,您无需编写循环即可获得代码 :P</p>
<pre><code>NSArray* arrRet = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(idevaluatedObject, NSDictionary<NSString *,id> * bindings) {
BOOL __block match = false;
[valuesArray enumerateObjectsUsingBlock:^(id__nonnull obj, NSUInteger idx, BOOL * __nonnull stop) {
*stop = match = .location != NSNotFound;
}];
return match;
}]];
</code></pre></p>
<p style="font-size: 20px;">关于ios - 检查字符串是否包含数组中的任何字符串,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/30987329/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/30987329/
</a>
</p>
页:
[1]