Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Replace a letter/word in string

How to replace a letter/word in a string? I tried .replacingOccurrences. It worked in the line of code but when I print the result, I went back to the original string.

Many thanks in advance.

Example code here.

var aString = ["This is my string"]

for s in aString { s.replacingOccurrences(of: "s", with: "++") print(s) }

1 Answer

Arman Arutyunov
Arman Arutyunov
21,900 Points

This method works with the whole string and you don't need to split it to letters. Even the name of the method tells you "occurrencES". That means it will analyse the whole string by itself and replace everything you described in the parameters anywhere it finds the "s" character in your case. Just call it from the original string and store the result inside a new constant. Then print it.

var aString = "This is my string"

let mutatedString = aString.replacingOccurrences(of: "s", with: "++")
print(mutatedString)