OneBite.Dev - Coding blog in a bite size

Replace Multiple Words In A String In Swift

Code snippet for how to Replace Multiple Words In A String In Swift with sample and detail explanation

Managing words in a string is a common task in software development and Swift makes it particularly easy. In this article, we’ll cover exactly how you can replace multiple words in a string using Swift’s sophisticated yet accessible programming tools.

Code snippet for replacing multiple words

Below is a simple, practical example of how to replace multiple words in a string in Swift:

let originalString = "I love to code in Python and Java."
let wordsToReplace = ["Python", "Java"]
let newWord = "Swift"
var newString = originalString
for word in wordsToReplace {
    newString = newString.replacingOccurrences(of: word, with: newWord)
}
print(newString)

Running this piece of code will output: “I love to code in Swift and Swift.”

Code Explanation for replacing multiple words

To understand how this Swift example works, let’s break it down step by step:

  1. We first define an originalString - this is a string value that contains the words we intend to replace.

  2. Next, we define a wordsToReplace array that contains the words to be replaced in the originalString.

  3. We specify the newWord - this is the string that will replace each occurrence of the words in the wordsToReplace array.

  4. We instantiate newString as a copy of originalString, which we’ll be modifying over the next steps.

  5. We then start a for-in loop over each word in wordsToReplace.

  6. Inside the loop, we use the replacingOccurrences(of:with:) method on newString, which comes with Swift’s String class. This replaces every occurrence of word with newWord in newString. The method returns a new string, which we assign back to newString.

  7. Finally, after the loop has executed for all the words in wordsToReplace, we print newString to see the result of the word replacement process.

Through this example, we see how simple and intuitive Swift makes the process of replacing multiple words in a string. Regardless of the complexity of your text manipulation requirements, Swift provides flexible and powerful tools to get the job done efficiently.

swift