How would you scan an array of strings for a set of substrings in objective-c?

后端 未结 5 1758
情歌与酒
情歌与酒 2021-01-27 03:21

So I basically have an array of words and phrases. Some of them contain curses. I want to create a method that automatically scans each of the units in the array for curses. If

5条回答
  •  面向向阳花
    2021-01-27 03:22

    If it is a rather small list just iterate through it checking each word.

    If it is rather large put the "bad words" in an NSOrderedSet and then use the method: containsObject:.

    If the number of words to be checked is not small you could also put the words to be checked in an NSSet and the "bad words" in another NSSet and use the method: intersectsSet:.

    Example:

    NSArray *stringsToCheck  = @[@"hey how are you", @"what is going on?", @"whats up dude?", @"do you want to get chipotle?"];
    NSSet *badWords = [NSSet setWithArray:@[@"how", @"dude", @"yes"]];
    for (NSString *line in stringsToCheck) {
        NSSet *checkWords = [NSSet setWithArray:[line componentsSeparatedByString:@" "]];
        NSLog(@"checkWords: %@", checkWords);
    
        if ([checkWords intersectsSet:badWords]) {
            NSLog(@"checkWords contains a bad word in: '%@'", [[checkWords allObjects] componentsJoinedByString:@" "]);
            // Now search for the specific bad word if necessary.
        }
    }
    

    NSLog output:
    checkWords contains a bad word in: 'you how are hey'

提交回复
热议问题