replace a substring in a string in swift

To replace a substring in a string in Swift, you can use the replacingOccurrences(of: String, with: String) method of the String class. This method replaces all occurrences of a substring with another string.

Here's an example:

main.swift
var str = "Hello, World!"
str = str.replacingOccurrences(of: "World", with: "Swift")
print(str) // outputs: "Hello, Swift!"
124 chars
4 lines

In the above example, we first create a string and assign it to str. Then, we use the replacingOccurrences(of:with:) method to replace all occurrences of "World" with "Swift". Finally, we print the updated string to the console.

Note that the replacingOccurrences(of:with:) method returns a new string with the replacements made. If you want to replace a substring in place, you need to assign the result back to the original string, as shown in the example above.

gistlibby LogSnag