I would like to create a predicate to search for a specific letter at the start of each word in a string of words e.g. all words starting with A in @"The man ate apples", would return ate and apples. Is it possible to create such a predicate? Thank you.
我想创建一个谓词来搜索一串单词中每个单词开头的特定字母,例如在@“男人吃苹果”中以A开头的所有单词都会返回吃饭和苹果。是否有可能创建这样的谓词?谢谢。
1 个解决方案
#1
2
An NSPredicate returns true or false when evaluated, so you cannot create a predicate that returns all the words starting with "a".
NSPredicate在计算时返回true或false,因此您无法创建返回以“a”开头的所有单词的谓词。
You can create a predicate that returns true for words starting with "a", then split the sentence to world, and filter the good words with predicate something like:
您可以创建一个谓词,对于以“a”开头的单词返回true,然后将该句子拆分为world,并使用谓词过滤好词:
NSArray *words = [sentence componentsJoinedByString:@" "];
NSPredicate *beginsWithA = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'a'"];
NSArray *wordsBeginsWithA = [words filteredArrayUsingPredicate:beginsWithA];
#1
2
An NSPredicate returns true or false when evaluated, so you cannot create a predicate that returns all the words starting with "a".
NSPredicate在计算时返回true或false,因此您无法创建返回以“a”开头的所有单词的谓词。
You can create a predicate that returns true for words starting with "a", then split the sentence to world, and filter the good words with predicate something like:
您可以创建一个谓词,对于以“a”开头的单词返回true,然后将该句子拆分为world,并使用谓词过滤好词:
NSArray *words = [sentence componentsJoinedByString:@" "];
NSPredicate *beginsWithA = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'a'"];
NSArray *wordsBeginsWithA = [words filteredArrayUsingPredicate:beginsWithA];