gpt4 book ai didi

iphone - 在 NSArray 中的字符串中搜索关键字

转载 作者:行者123 更新时间:2023-11-29 03:37:44 26 4
gpt4 key购买 nike

我有一个关键字数组和一个字符串数组

我目前正在迭代关键字,并在字符串数组上使用过滤器来确定关键字是否在其中(以某种形式)。

下面的代码可以工作,但是当另一个单词中存在关键字(或与关键字相同的字符)时,就会对此进行标记。 IE。在字符串 ribbon 中搜索 bon 将标记功能区。我不想进行精确的比较,因为关键字可能会被字符串中的其他字符/单词包围。

有没有办法可以搜索它并且仅在它被空格或括号包围时标记它? IE。不是另一个单词的一部分..

NSArray *paInc = [productIncludes valueForKey:pa];
// This is the array of keywords

NSMutableArray *paMatchedIncludes = [[NSMutableArray alloc] init];

for (id include in paInc){

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", include];
NSArray *filteredArray = [stringArray filteredArrayUsingPredicate:predicate];
// stringArray is the array containing the strings I want to search for these keywords

for (NSString *ing in filteredArray){
if ([ing length] > 0){
if (![paMatchedIncludes containsObject:[NSString stringWithFormat:@"%@",ing]]){
[paMatchedIncludes addObject:[NSString stringWithFormat:@"%@",ing]];
}
}
}

}

最佳答案

下面的代码可以解决您的问题吗?

NSArray *paInc = @[@"bon",
@"ssib"];
// This is the array of keywords

NSArray *stringArray = @[@"Searching for bon in string ribbon would flag ribbon.",
@"I don't want to do an exact comparison as it's possible the keyword will be surrounded by other characters / words in the string."];
// stringArray is the array containing the strings I want to search for these keywords

NSMutableArray *paMatchedIncludes = [[NSMutableArray alloc] init];

for (id include in paInc){ // for every keyword
for (NSString *nextString in stringArray) { // for every string
NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
if ([components containsObject:include]) {
[paMatchedIncludes addObject:nextString];
}
}
}

编辑(由于您的评论):对于不区分大小写的比较:

for (id include in paInc){ // for every keyword
for (NSString *nextString in stringArray) { // for every string
NSArray *components = [nextString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ()"]];
for (NSString *nextComponent in components) {
if([nextComponent caseInsensitiveCompare:include] == NSOrderedSame)
[paMatchedIncludes addObject:nextString];
}
}
}

关于iphone - 在 NSArray 中的字符串中搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18911071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com