How can I replace a specific word in a string in swift?

I am looking for a way to replace a word within a string in swift. Can anyone please help?

this is what I have so far, I can find a specific word, but I don't know how to replace it ...

     var str = "helo, playgound"

     var findWords = ["helo","playgound"]
     var replaceWords = ["hello","playground"]

extension String {
    var wordList:[String] {
        return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())).componentsSeparatedByString(" ")
    }
}

func stringToArray() -> Array<String> {
    var arr = str.wordList
    return arr
}

func correction(var _arr:Array<String>) -> String{

    for var i = 0; i < _arr.count; i++ {
            if str.lowercaseString.rangeOfString(findWords[i]) != nil {
                println("exists")
        }
      }
  return str
}

      

+3


source to share


2 answers


It depends on your definition of the word. If you're looking for a smart built-in "word" concept, the simplest solution is probably to use NSRegularExpression, which knows where the "word boundaries" are:

var s = NSMutableString(string:"hello world, go to hell")
let r = NSRegularExpression(
    pattern: "\\bhell\\b",
    options: .CaseInsensitive, error: nil)!
r.replaceMatchesInString(
    s, options: nil, range: NSMakeRange(0,s.length),
    withTemplate: "heaven")

      

After that, s

there is "hello world, go to heaven"

what is the right answer; we replaced "hell", that word, but not "hell" with "hello". Please note that we are also case insensitive and not case sensitive, which seems to be one of your wishes.



This example shows how to make only one pair ("hell" and "heaven"), but it's easy to abstract it in a method so you can do it over and over for further pairs:

var str = "helo, playgound"

var findWords = ["helo", "playgound"]
var replaceWords = ["hello", "playground"]

func correct(str:String, orig:String, repl:String) -> String {
    var s = NSMutableString(string:str)
    let r = NSRegularExpression(
        pattern: "\\b\(orig)\\b",
        options: .CaseInsensitive, error: nil)!
    r.replaceMatchesInString(
        s, options: nil, range: NSMakeRange(0,s.length),
        withTemplate: repl)
    return s
}

for pair in Zip2(findWords,replaceWords) {
    str = correct(str, pair.0, pair.1)
}

str // hello, playground

      

+3


source


The easiest way is to do this:

let statement = "Swift is hard."
let swiftRange = statement.startIndex..<advance(statement.startIndex, 5)
let newStatement = statement.stringByReplacingCharactersInRange(swiftRange, withString: "Objective-C")
// now newStatement = "Objective-C is hard."

      

Following a long commenting tour: the above is in the OP's guess, "I can find a specific word, but I don't know how to replace it ...", so it's not about finding a "word" that defines another discussion. It's just a replacement for an already found word.



Another word on stringByReplacingCharactersInRange

: @matt claims to be a Cocoa junction. In this case, Apple is telling a lie: enter image description here

I created a website, but no Apple source told anything. Foundation method only for NSString. Their Quick Book was also silent (in many ways). Well, I don't trust Apple anymore since Yosemite-fail.

0


source







All Articles