我正在寻找一种方法来取代字符在一个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的命名约定,提出一个合适的函数名。
其他回答
这是一个在字符串上的替换方法的扩展,它没有不必要的复制,并在适当的地方做所有事情:
extension String {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
(方法签名也模仿内置String.replacingOccurrences()方法的签名)
可用于以下方式:
var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"
Xcode 11•Swift 5.1
StringProtocol replacingOccurrences的突变方法可以实现如下:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
我实现了这个非常简单的func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
所以你可以这样写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
输出是
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的命名约定,提出一个合适的函数名。