Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2
I am still not sure if this is exactly what you are asking but if I understood correctly you can zip your collections and iterate the resulting tuples:
var result = "example"
zip(["e", "x", "a", "m", "p", "l", "e"],["1", "3", "2", "8", "5", "7"]).forEach {
result = result.replacingOccurrences(of: $0, with: $1, options: .literal)
}
result // 1328571
What is an easier way to replace multiple characters with other characters in a string in swift?
I think the only problem you will run into with using addingPercentEncoding is that your question states that a space " " should be replaced with an underscore. Using addingPercentEncoding for a space " " will return %20. You should be able to combine some of these answers, define the remaining characters from your list that should return standard character replacement and get your desired outcome.
var userText = "This has.lots-of(symbols),&stuff"
userText = userText.replacingOccurrences(of: " ", with: "_")
let allowedCharacterSet = (CharacterSet(charactersIn: ".-(),&").inverted)
var newText = userText.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
print(newText!) // Returns This_has%2Elots%2Dof%28symbols%29%2C%26stuff
Replacing Multiple Occurrences in Array - Swift 4.1
extension Array where Element: Equatable {
func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {
var newArr: Array<Element> = self
for replacement in array {
for (index, item) in self.enumerated() {
if item == replacement.of {
newArr[index] = replacement.with
}
}
}
return newArr
}
}
Swift 5 replacingOccurrences multiple elements
xTwisteDx’s answer is correct. Just chain your replacingOccurrences
calls.
But just a stylistic observation: Frequently, when chaining a bunch of calls like this, we might break it into separate lines, e.g.
let newOsetx = osetx
.replacingOccurrences(of: "e", with: "11")
.replacingOccurrences(of: "t", with: "10")
When you're doing a bunch of replacements, that can make it a little more easy to read the code at a glance.
If you are doing more than two or three replacements, you might consider using some looping pattern. For example, you could use an array of tuples representing the search and replace strings:
let replacements = [
("e", "11"),
("t", "10")
]
Then you can loop through them, performing the replacements:
var newOsetx = osetx
for (searchString, replacement) in replacements {
newOsetx = newOsetx.replacingOccurrences(of: searchString, with: replacement)
}
Or you can use reduce
:
let newOsetx = replacements.reduce(osetx) { string, replacement in
string.replacingOccurrences(of: replacement.0, with: replacement.1)
}
Combine multiple replacingOccurrences() with Swift
You may use
var modString = myString.replacingOccurrences(of: "[#*_]", with: "\\\\$0", options: [.regularExpression])
With a raw string literal:
var modString = myString.replacingOccurrences(of: "[#*_]", with: #"\\$0"#, options: [.regularExpression])
Result: This is \#an exemple \#of \_my\_ \* function
The options: [.regularExpression]
argument enables the regex search mode.
The [#*_]
pattern matches #
, *
or _
and then each match is replaced with a backslash (\\\\
) and the match value ($0
). Note that the backslash must be doubled in the replacement string because a backslash has a special meaning inside a replacement pattern (it may be used to make $0
a literal string when $
is preceded with a backslash).
How to replace multiple characters in swift
Using replacingOccurrences
means that you would like to replace occurrences of string within string. So basically you would use it to replace all occurrences of "dog" with "cat". It means that "I have a dog. My dog is very neat..." would be converted to "I have a cat. My cat is very neat...".
From what your seem to try to do is to actually filter out some of the characters. You could try an answer like this one. With some small tweaks you should probably get something like
let textA = text.filter { "[ a|\\b|\\u]".contains($0) == false }
So basically you would like to have a same text but removing all characters that are contained within the string "[ a|\\b|\\u]"
.
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
.
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
})
Related Topics
How to Read Code Block After a Function Call
Datefromstring() Returns Incorrect Date
Stopping Timer at Defined Amount of Time in Swift
Swift Error: Cannot Convert of Type '()' to Specified Type 'Bool'
How to Properly Test Against Certain Values in Nseventmodifierflags via Swift
How to Define an Array of a Particular Enum Case in Swift
How to Check for Value in Firebase That Is Held Under a Autoid Child
.Sink Is Not Returning the Promise Values from a Future Publisher
Check If the Username Exist in Firebase
After Getting Image from Uiimagepickercontroller, Uiimageview Rotates Image for iPhone 5
Swift: Can't Edit Properties of Custom Table Cell Programmatically
Declaring Conformance to @Objc Protocol in Empty Extension Breaks with Exc_Bad_Instruction
How to Unpack Multiple Levels of Nested JSON in Firebase Database
Elegant 'Bounded' Methodology in Swift
Where to Place App Delegate Code in App.Swift File