OnlyPrograming OnlyPrograming - 1 year ago 77
iOS Question

Remove a word from unknown length of string SWIFT

I am trying to remove a word from unknown lengh of a string, here is my code.

if (newService.range(of: serviceStr) != nil){

// I should remove selected word here

print("remove selected")
print("add select")
let space = " , "
newService = newService + space + serviceStr

I have tried many ways, however, every code I should specify the offsetBy which I dont know because its user buttons selection.

Answer Source

You can write

import Foundation

var sentence = "This is a simple sentence"
let wordToRemove = "simple"

if let range = sentence.range(of: wordToRemove) {

print(sentence) // This is a  sentence

If you also want remove the additional space after the simple word replace this

let wordToRemove = "simple"

with this

let wordToRemove = "simple "
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download