How could I replace nth character of a String
with another one?
func replace(myString:String, index:Int, newCharac:Character) -> String { // Write correct code here return modifiedString }
For example, replace("House", 2, "r")
should be equal to "Horse"
.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
To replace or substitute all occurrences of one character with another character, you can use the substitute function. The SUBSTITUTE function is full automatic. All you need to do is supply "old text" and "new text". SUBSTITUTE will replace every instance of the old text with the new text.
Solutions that use NSString
methods will fail for any strings with multi-byte Unicode characters. Here are two Swift-native ways to approach the problem:
You can use the fact that a String
is a sequence of Character
to convert the string to an array, modify it, and convert the array back:
func replace(myString: String, _ index: Int, _ newChar: Character) -> String { var chars = Array(myString) // gets an array of characters chars[index] = newChar let modifiedString = String(chars) return modifiedString } replace("House", 2, "r") // Horse
Alternately, you can step through the string yourself:
func replace(myString: String, _ index: Int, _ newChar: Character) -> String { var modifiedString = String() for (i, char) in myString.characters.enumerate() { modifiedString += String((i == index) ? newChar : char) } return modifiedString }
Since these stay entirely within Swift, they're both Unicode-safe:
replace("🏠🏡🏠🏡🏠", 2, "🐴") // 🏠🏡🐴🏡🏠
In Swift 4 it's much easier.
let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)
This is an example:
let oldString = "Hello, playground" let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)
where the result is
Hell0, playground
The type of newString
is Substring. Both prefix
and dropFirst
return Substring
. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With