user1457381
user1457381

Reputation:

Find and Replace in Swift

Hi I have two arrays.

var firstArray = ["Hi", "Hello", "Mother"]
var secondArray = ["Yo", "Yee", "Father"]

Now say I did a println("I saw Johnny and said Hi") but it would really replace it with my second string object which is "Yo"

So pretty much replace everything in the first array with the second array in the exactly order they're in anytime someone typed any literal string in the first array? I'm trying to do this in swift. I tried looping through the first array with stringByReplacingOccurrencesOfString but I'm not sure how I can implement an NSArray into it. Any help?


What if I did below?

var myString = "Hello this is a test."
var myDictionary = ["Hello":"Yo"]

for (originalWord, newWord) in myDictionary {
    let newString = aString.stringByReplacingOccurrencesOfDictionary(myString, withString:newWord, options: NSStringCompareOptions.LiteralSearch, range: nil)
}

I still can't figure out how if I put that into an println("hello how are you?) if it'll automatically know to replace "hello" every time it's entered in the println statement with "yo"

Upvotes: 1

Views: 1542

Answers (2)

Mike S
Mike S

Reputation: 42335

You're pretty close with your idea of using a dictionary, you just need to keep replacing myString instead of creating a new string each time, and call stringByReplacingOccurrencesOfString correctly:

var myString = "Hello this is a test."
var myDictionary = ["Hello":"Yo"]

for (originalWord, newWord) in myDictionary {
    myString = myString.stringByReplacingOccurrencesOfString(originalWord, withString:newWord, options: NSStringCompareOptions.LiteralSearch, range: nil)
}

println(myString)

Outputs:

Yo this is a test.

Upvotes: 5

Caroline
Caroline

Reputation: 4970

If the object in the array conforms to the Equatable protocol, (String does conform), then you can use find()

Try this in a playground:

import UIKit

var firstArray = ["Hi", "Hello", "Mother"]
var secondArray = ["Yo", "Yee", "Father"]

var index = find(firstArray, firstArray[0])

println("first string: \(firstArray[0])")
println("replaced: \(secondArray[index!])")

Upvotes: 0

Related Questions