I am looking for a way to replace characters in a Swift String
.
Example: \"This is my string\"
I would like to replace \" \" with \"+\" to get \
Less happened to me, I just want to change (a word or character) in the String
So I've use the Dictionary
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
usage
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
Swift 3 solution based on Ramis' answer:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
Tried to come up with an appropriate function name according to Swift 3 naming convention.
If you don't want to use the Objective-C NSString
methods, you can just use split
and join
:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })
returns an array of strings (["This", "is", "my", "string"]
).
join
joins these elements with a +
, resulting in the desired output: "This+is+my+string"
.
You can use this:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
If you add this extension method anywhere in your code:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
Swift 3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
Did you test this :
var test = "This is my string"
let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
I've implemented this very simple func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
So you can write:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')