我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
当前回答
基于Ramis回答的Swift 3解决方案:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
尝试根据Swift 3的命名约定,提出一个合适的函数名。
其他回答
一个快速的解决方案沿着Sunkas的路线:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Use:
var string = "foo!"
string.replace("!", with: "?")
print(string)
输出:
foo?
修改现有可变字符串的类别:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
使用:
name.replace(" ", withString: "+")
这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
斯威夫特5.5
我正在使用这个扩展:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
let components = components(separatedBy: characterSet)
let result = components.joined(separator: toSeparator)
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters: characters, toSeparator: "")
}
}
用法:
"<34353 43434>".replaceCharacters(characters: "< >", toSeparator:"+") // +34353+43434+
"<34353 43434>".wipeCharacters(characters: "< >") // 3435343434
我实现了这个非常简单的func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
所以你可以这样写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')