Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nth character of a string with another

Tags:

string

swift

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".

like image 757
Piercy Avatar asked Jul 16 '14 19:07

Piercy


People also ask

How do you replace a character in a string with another?

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.

What replaces one character with another?

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.


2 Answers

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, "🐴") // 🏠🏡🐴🏡🏠 
like image 197
Nate Cook Avatar answered Sep 20 '22 20:09

Nate Cook


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.

like image 27
Luca Torella Avatar answered Sep 21 '22 20:09

Luca Torella