Replace
In Swift 5.8, we can change ranges of characters in strings. With replaceSubrange
we can replace them with another string
. We use index()
to create a range.
When replacing strings in Swift, we often combine multiple methods. We combine index()
and replacement methods like replaceSubrange
.
In this program we first declare a string
. This string
has a substring "red" in it. We next call replaceSubrange
with a range.
replaceSubrange
. We use index()
on the string
to get the bounds. We advance 6 chars.string
. We base the end also on the startIndex
.ReplaceSubrange
changes the string
"red" in the string to "yellow." The string
remains colorful.var value = "green red blue" print(value) // Replace range at positions 6 through 9. // ... Specify a replacement string. let start = value.index(value.startIndex, offsetBy: 6); let end = value.index(value.startIndex, offsetBy: 6 + 3); value.replaceSubrange(start..<end, with: "yellow") print(value)green red blue green yellow blue
This program loops through the chars in a string
. It then uses an if-else
block to change some chars in the string. The value "1" is changed.
string
. A more complex data structure (dictionary) could be used.Append()
adds a char
to a string
. We build up a new string
in the for
-loop.var value = "123abc123" var result = String() // Replace individual characters in the string. // ... Append them to a new string. for char in value { if char == "1" { let temp: Character = "9" result.append(temp) } else { result.append(char) } } print(result)923abc923
ReplacingOccurrences
In Foundation we find some string
replacement methods. With replacingOccurrences
we replace all occurrences of one substring with another.
import Foundation let text = "cats and dogs" // Replace cats with birds. // ... Use Foundation method. let result = text.replacingOccurrences(of: "cats", with: "birds") // Print result. print(result)birds and dogs
ReplacingCharacters
Here we use replacingCharacters
. This may have the same effect as the replaceSubrange
method in Swift. It replaces a range with a substring.
import Foundation let letters = "ZZZY" // Replace first 3 characters with a string. let start = letters.startIndex; let end = letters.index(letters.startIndex, offsetBy: 3); let result = letters.replacingCharacters(in: start..<end, with: "WH") // The result. print(result)WHY
Strings in Swift are accessed through ranges, along with startIndex
and endIndex
. To replace chars, we access a range and invoke replaceSubrange
.