Any Way to Replace Characters on Swift String

Any way to replace characters on Swift String?

This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.

You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.

let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")

Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

let aString = "Some search text"

let replaced = String(aString.map {
$0 == " " ? "+" : $0
})

Replace characters in Swift String?

You use cijfers.replacingOccurrences not on the correct way, for your purpose.
Try this:

let str = "38,5"
let replaced = str.replacingOccurrences(of: ",", with: ".")
print(replaced)

How to replace a substring in a string in Swift

You can try using replacingOccurrences(of:with:).
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string

sample example :

let str = "Swift 4.0 is the best version of Swift to learn, so if you're starting fresh you should definitely learn Swift 4.0."
let replaced = str.replacingOccurrences(of: "4.0", with: "5.0")

How to replace all characters of a String with another character in Swift?

If you just want to replace the entire string, "Apples", with "??????" — init(repeating:count:) should work fine.

let string = "Apples"
let obscured = String(repeating: "?", count: string.count)
print(obscured)

Result:

??????

Replace all characters in a String in Swift

Another way:

let outputString = inputString.replacingOccurrences(of: "[^\\s]",
with: " ",
options: .regularExpression,
range: inputString.startIndex..<inputString.endIndex)

Swift - Replace exact matching Characters / Words in String (not containing)

You just need to use replacingOccurences(of:with:options:) and pass .regularExpression to options. You also need to pass a regex to of: now instead of just passing the substring you want to replace. The correct regex here if \\bc\\b, which matches a word boundary before and after c ensuring that it's just the char c you are matching and not a c that's part of a word/expression.

let string = "c \\cdot c"
let replacingString = string.replacingOccurrences(of: "\\bc\\b", with: "2", options: .regularExpression)
print(replacingString) // "2 \\cdot 2"

Replace specific characters in string in Swift

If you want to replace all word characters, you can use the regularExpressions input to the options parameter of the same function you were using before, just change the specific String input to \\w, which will match any word characters.

let str = "Hello World"
let replace = str.replacingOccurrences(of: "\\w", with: "_", options: .regularExpression) // "_____ _____"

Bear in mind that the \\w won't replace other special characters either, so for an input of "Hello World!", it will produce "_____ _____!". If you want to replace every character but whitespaces, use \\S.

let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)

How to replace string into string in Swift?

You can try using stringByReplacingOccurrencesOfString

let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")

Edit
In Swift 5

import Foundation

let string = "Big red car"
let replaced = string.replacingOccurrences(of: "Big", with: "Small")

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.



Related Topics



Leave a reply



Submit