Swift - Using Replacerange() to Change Certain Occurrences in a String

swift - using replaceRange() to change certain occurrences in a string

This is is what you want to do:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
animal.replaceRange(range, with: "e")
}

rangeOfString will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.

we need to unwrap the optional and the safest way is with an if let statement so we assign our range to the constant range.

The replaceRange will do as it suggests, in this case we need animal to be a var.

Replace occurrences in String

Create an array with the new strings. Find the range of first matching substring "black" in the string using range(of:). And replace with the new string in the range using replaceSubrange(_:with:) method.
Then continue the loop till last element of the array.

var mString = "my car is black, my phone is black"
["blue","red"].forEach {
if let range = mString.range(of: "black") {
mString.replaceSubrange(range, with: $0)
}
}
print(mString)

my car is blue, my phone is red

Check Swift String Cheat Sheet

Replace string subrange with character and maintain length in Swift

How about building the string with the first three characters (prefix(3)) the created asterisk substring and the last three characters (suffix(3))

func hideInfo(sensitiveInfo: String) -> String {
let length = sensitiveInfo.utf8.count
if length <= 6 { return sensitiveInfo }
return String(sensitiveInfo.prefix(3) + String(repeating: "*", count: length - 6) + sensitiveInfo.suffix(3))
}

How to Replace specific range of string with a character?

There's a way to write that in Swift in one line:

let stringA = "1234567890"
let stringB = String(stringA.enumerated().map { !(5...7).contains($0) ? $1 : "*" })
let stringC = String(stringA.enumerated().compactMap { !(5...7).contains($0) ? $1 : $0 == 5 ? "*" : nil })

print(stringB) // "12345***90\n"
print(stringC) // "12345*90\n"

Just to add some explanation:
We enumarate the String so we can use the indexes to map the Characters based on their position on the String. On the closure, $0 corresponds to the offset and $1 to the Character on the iteration. It could also be written as $0.offset and $0.element, respectively.

On the second example with stringC, where it replaces with only one *, we replace the Character in position 5 with the * and the rest with nil, and the compactMap will return all of the non-nil results.

How to replace the specific range of characters in String only once

A small function like this would make more sense,

func bySubstitutingZeros(number: String) -> String {
if number.hasPrefix("00") {
return "+" + number[number.index(number.startIndex, offsetBy: 2)...]
}
return number
}

Or you can as well create an extension on String class,

extension String {

func byReplacingPrefix(_ prefix: String, with replacement: String) -> String {
if self.hasPrefix(prefix) {
return replacement + self[index(startIndex, offsetBy: prefix.count)...]
}
return self
}
}

"0035850582919023".byReplacingPrefix("00", with: "+")

Output:

+35850582919023

How to replace letters at specific positions in swift

An alternative to replacing characters in strings is to turn the word into an array of String and replace the letters directly. Use .joined() to turn that array back into a String:

// the hidden word is elephant
let word = "elephant"
let wordArray = word.map(String.init)
print(wordArray)

["e", "l", "e", "p", "h", "a", "n", "t"]

var hidden = Array(repeating: "x", count: word.count)
print(hidden)

["x", "x", "x", "x", "x", "x", "x", "x"]

let guessedLetter = "e"

// now fill in a guessed letter
for index in hidden.indices {
if wordArray[index] == guessedLetter {
hidden[index] = guessedLetter
}
}

// turn array back into a String with joined()
print(hidden.joined())

exexxxxx

How to replace nth character of a string with another

Please see NateCook answer for more details

func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
var chars = Array(myString.characters) // gets an array of characters
chars[index] = newChar
let modifiedString = String(chars)
return modifiedString
}

For Swift 5

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

This is no longer valid and deprecated.

You can always use swift String with NSString.So you can call NSString function on swift String.
By old stringByReplacingCharactersInRange: you can do like this

var st :String = "House"
let abc = st.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r") //Will give Horse

Swift: replace character in string - without stringByReplacingOccurrencesOfString

What about this? Combine all characters to a string by "reducing" them with the +
operator:

let str = Array(characters).reduce("", combine: +)
println(str)
// Output: my string, hello

Update: An alternative (perhaps nicer) solution:

var str = ""
str.extend(characters)

Using extend(), the string replacement could be done without an intermediate Array:

let myString = "my string: hello" as String
var myNewString = ""
myNewString.extend(map(myString.generate(), {$0 == ":" ? "," : $0} ))

String methods in Swift to replace the first character in a string

You can take the user input string and pad it with '_':

var userInput = "1" // This is the string from the text field input by the user

var finalText = userInput.stringByPaddingToLength(3, withString: "_", startingAtIndex: 0)


Related Topics



Leave a reply



Submit