NSPredicate 将单词数组过滤为字母数组

发布于 2024-09-10 12:09:11 字数 592 浏览 0 评论 0原文

我正在尝试在创建单词时制作“加权”字母列表。我在 NSArray 中有大量单词列表。例如,我试图获取一个新的 NSArray,其中根据输入的前两个字母仅填充所有单词的第三个字母。

到目前为止,我已经......

NSArray *filteredArray;
if (currentWordSize == 0) {
    filteredArray = wordDictionary
}
else {
    NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", filterString];
    filteredArray = [wordDictionary filteredArrayUsingPredicate:filter];
}

这对于将整个单词放入过滤数组中来说非常有效,但这并不是我所需要的。谁能告诉我一种方法,只用 wordDictionary 中随机 NSString 的第一个、第二个或第三个字母填充 filteredArray

编辑:澄清了我的问题。

I am trying to make "weighted" list of letters as words are created. I have a massive list of words in an NSArray. For example I am trying to acquire a new NSArray filled with just the 3rd letters of all the words based off the first two letters entered.

So far I have...

NSArray *filteredArray;
if (currentWordSize == 0) {
    filteredArray = wordDictionary
}
else {
    NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF beginswith[cd] %@", filterString];
    filteredArray = [wordDictionary filteredArrayUsingPredicate:filter];
}

And that works all good for putting whole words into the filtered array, but that isn't exactly what I need. Can anyone show me a way to just fill the filteredArray with just the 1st, 2nd, or 3rd letters of a random NSString from the wordDictionary?

EDIT: clarified my question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪淡了忧伤 2024-09-17 12:09:11

NSPredicate 不是您想要使用的。 NSPredicate 只是根据一个或多个条件评估对象并返回是/否结果,因此它不能用于执行实际操作正在测试的项目的操作。

要获取数组中每个字符串的第三个字母并将结果放入新数组中,将如下所示:

NSArray* wordDictionary;
NSMutableArray* filteredArray = [[NSMutableArray alloc] init];

for (NSString* aString in wordDictionary)
{
    if ([aString length] > 2)
        [filteredArray addObject:[aString substringWithRange:NSMakeRange(2, 1)]];
    else
        [filteredArray addObject:@""]; //there is no third letter
}

NSPredicate isn't what you're going to want to use for this. NSPredicate simply evaluates objects based on one or more criteria and returns a yes/no result, so it can't be used to do things that actually manipulate the items being tested.

To grab the third letter of each string in an array and put the results in a new array would look something like this:

NSArray* wordDictionary;
NSMutableArray* filteredArray = [[NSMutableArray alloc] init];

for (NSString* aString in wordDictionary)
{
    if ([aString length] > 2)
        [filteredArray addObject:[aString substringWithRange:NSMakeRange(2, 1)]];
    else
        [filteredArray addObject:@""]; //there is no third letter
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文