Home > database >  How can I find repeated words and separate from sentences?
How can I find repeated words and separate from sentences?

Time:05-25

For example. I have string value like this :

var str = "asdImverygreatfullasdandeverythingwillbegoodandIwillbehappy"

there is 'asd' and 'and' these two words repeat between sentences. I want to find these two words and remove from str. Is that possible?

Desire output will be :

str = "ImverygreatfulleverythingwillbegoodIwillbehappy"

CodePudding user response:

You can do something like this : -

     var str = "asdImverygreatfullasdandeverythingwillbegoodandIwillbehappy"
     str = str.replacingOccurrences(of: "asd", with: "")
     str = str.replacingOccurrences(of: "and", with: "")
     print("Answer : - \(str)")

Your Answer will be

     Answer : - ImverygreatfulleverythingwillbegoodIwillbehappy

CodePudding user response:

An efficient way is to replace the substrings with help of Regular Expression

let str = "asdImverygreatfullasdandeverythingwillbegoodandIwillbehappy"
let cleaned = str.replacingOccurrences(of: "a(s|n)d", with: "", options: .regularExpression)

"a(s|n)d" means find both "asd" and "and"

  • Related