我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
当前回答
斯威夫特4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
输出:
result : Hello_world
其他回答
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
我实现了这个非常简单的func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
所以你可以这样写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
你可以用这个:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
如果你在你的代码中添加这个扩展方法:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
斯威夫特3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
这是一个在字符串上的替换方法的扩展,它没有不必要的复制,并在适当的地方做所有事情:
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"