Search code examples
iosobjective-cswiftnsstringnsarray

remove exact word phrase from string in Swift or Objective-C


I would like to remove an exact combination of words from a string in Swift or Objective-C without removing portions of a word.

You can remove a single word from a string by converting the strings into arrays:

NSString *str = @"Did the favored horse win the race?";
NSString *toRemove = @"horse";

NSMutableArray *mutArray = [str componentsSeparatedByString:@" "];
NSArray *removeArray = [toRemove componentsSeparatedByString:@" "];
[mutarr removeObjectsInArray:removeArr];

You can also remove a two word string from another string if you don't care about whole words using:

str = [str stringByReplacingOccurrencesOfString:@"favored horse " withString:@""];

although you have to work around the spacing issue.

This would fail, however, on a string such as:

str = [str stringByReplacingOccurrencesOfString:@"red horse " withString:@""];

Which would give "Did the favo horse win the race"

How can you remove a multiple word term cleanly without removing partial words leaving fragments?

Thanks for any suggestions.


Solution

  • // Convert string to array of words
    let words = string.components(separatedBy: " ")
    
    // Do the same for your search words
    let wordsToRemove = "red horse".components(separatedBy: " ")
    
    // remove only the full matching words, and reform the string
    let result = words.filter { !wordsToRemove.contains($0) }.joined(separator: " ")
    
    // result = "Did the favored win the race?"
    

    The caveat to this method is that it will remove those exact words anywhere in your original string. If you want the result to only remove the words where they appear in that exact order, then just use a space at the front of the parameter for replacingOccurrencesOf.