C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument: We pass a range to replaceSubrange. We use index() on the string to get the bounds. We advance 6 chars.
End: We use a range operator to advance to 9 chars into the string. We base the end also on the startIndex.
Range: half-openResult: ReplaceSubrange changes the string "red" in the string to "yellow." The string remains colorful.
Swift program that replaces string with replaceSubrange
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)
Output
green red blue
green yellow blue
Tip: This approach can be used to translate chars in a string. A more complex data structure (dictionary) could be used.
DictionaryAppend: This method adds a char to a string. We build up a new string in the for-loop.
Swift program that replaces characters
var value = "123abc123"
var result = String()
// Replace individual characters in the string.
// ... Append them to a new string.
for char in value.characters {
if char == "1" {
let temp: Character = "9"
result.append(temp)
}
else {
result.append(char)
}
}
print(result)
Output
923abc923
Here: We change the word "cats" to "birds." This might make the "dogs" part happier.
Swift program that uses replacingOccurrences
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)
Output
birds and dogs
Swift program that uses replacingCharacters
import Foundation
let letters = "zzzy"
// Replace first three 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)
Output
why