JSharpp
JSharpp

Reputation: 559

Removing an array of words from a string

I have data that includes certain words that I do not want to display. I am trying to remove these set of words from the string before displaying it to the label. With the code I have, I can do this word by word, but have to type out the code X amount of times to achieve it for each word. What would be the correct method to remove the set of words at once?

Here is the code I'm currently using:

 let remove = ["Production", "Productions", "Studio", "Studios", 
"Entertainment", "Pictures", "Company", "Films", "Media"]
                if let range = string.range(of: remove) {
                    string.removeSubrange(range)
                }
                self.label.text = string

With this code I receive this error on the range line:

Argument type '[String]' does not conform to expected type 'StringProtocol'

Upvotes: 0

Views: 69

Answers (3)

Rawand Ahmed Shaswar
Rawand Ahmed Shaswar

Reputation: 2571

You can specify the allowed words, and then use Filter to remove the unwanted words:

var strings = ["Hello","Playground","World","Earth"]

var allowedStrings = "Playground Earth" // Specify using space
let seperated:[String] = allowedStrings.components(separatedBy: " ")

for i in seperated {
    if strings.contains(i) {
        strings = strings.filter{$0 != i}
    }
}
print(strings)   // ["Playground", "Earth"]

Upvotes: 0

vadian
vadian

Reputation: 285150

The error is clear.

The argument of range(of is a String not an array ([String])

You need a loop

let wordsToRemove = ["Production", "Productions", "Studio", "Studios", "Entertainment", "Pictures", "Company", "Films", "Media"]
for word in wordsToRemove {
   if let range = string.range(of: word) {
      string.removeSubrange(range)
   }
}
self.label.text = string

An alternative is regular expression

let trimmedString = string.replacingOccurrences(of: "(Productions?|Studios?|Entertainment|Pictures|Company|Films|Media)",
                                             with: "",
                                          options: .regularExpression)
self.label.text = trimmedString

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100533

You can try

remove.forEach {
   if let range = string.range(of:$0) {
     string.removeSubrange(range)
  }
}

as range(of:) expects a string not array

Upvotes: 1

Related Questions