任何方式来replaceSwiftstring上的字符?
我正在寻找一种方法来replaceSwift String
。
例如: "This is my string"
我想replace 用
+
得到: "This+is+my+string"
。
我怎样才能做到这一点?
Swift 3已经更新了这个答案。 如果您仍在使用Swift 1或2,请参阅修订历史logging。
你有几个select。 你可以像@jaumard所build议的那样使用replaceOccurrences replacingOccurrences()
let aString = "This is my string" let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
正如下面的@cprcrack指出的那样, options
和range
参数是可选的,所以如果你不想指定string比较选项或范围来进行replace,你只需要下面的内容。
let aString = "This is my string" let newString = aString.replacingOccurrences(of: " ", with: "+")
或者,如果数据是这样的特定格式,那么您只需要replace分隔字符,就可以使用components()
将string拆分为数组,然后使用join()
函数将其放回与指定的分隔符一起。
let toArray = aString.components(separatedBy: " ") let backToString = toArray.joined(separator: "+")
或者,如果你正在寻找一个不使用NSString API的Swifty解决scheme,你可以使用它。
let aString = "Some search text" let replaced = String(aString.characters.map { $0 == " " ? "+" : $0 })
你可以使用这个:
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) } }
Swift 3:
extension String { func replace(target: String, withString: String) -> String { return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil) } }
Swift 3解决scheme
let exampleString = "Example string" //Solution suggested above in Swift 3.0 let stringToArray = exampleString.components(separatedBy: " ") let stringFromArray = stringToArray.joined(separator: "+") //Swiftiest solution let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
你testing了这个:
var test = "This is my string" let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
一个Swift 3解决scheme沿着Sunkas的:
extension String { mutating func replace(_ originalString:String, with newString:String) { self = self.replacingOccurrences(of: originalString, with: newString) } }
使用:
var string = "foo!" string.replace("!", with: "?") print(string)
输出:
foo?
我正在使用这个扩展名:
extension String { func replaceCharacters(characters: String, toSeparator: String) -> String { let characterSet = NSCharacterSet(charactersInString: characters) let components = self.componentsSeparatedByCharactersInSet(characterSet) let result = components.joinWithSeparator("") return result } func wipeCharacters(characters: String) -> String { return self.replaceCharacters(characters, toSeparator: "") } }
用法:
let token = "<34353 43434>" token.replaceCharacters("< >", toString:"+")
修改现有可变string的类别:
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: "+")
基于Ramis的 Swift 3解决scheme的答案 :
extension String { func withReplacedCharacters(_ characters: String, by separator: String) -> String { let characterSet = CharacterSet(charactersIn: characters) return components(separatedBy: characterSet).joined(separator: separator) } }
试图根据Swift 3命名约定提出一个适当的函数名称。
这里是Swift 3的例子:
var stringToReplace = "This my string" if let range = stringToReplace.range(of: "my") { stringToReplace?.replaceSubrange(range, with: "your") }
如果你不想使用Objective-C的NSString
方法,你可以使用split
和join
:
var string = "This is my string" string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })
返回一个string数组( ["This", "is", "my", "string"]
)。
join
join这些元素+
,产生所需的输出: "This+is+my+string"
。
我已经实现了这个非常简单的function:
func convap (text : String) -> String { return text.stringByReplacingOccurrencesOfString("'", withString: "''") }
所以你可以写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
我认为正则expression式是最灵活和最稳定的方式:
var str = "This is my string" let regex = try! NSRegularExpression(pattern: " ", options: []) let output = regex.stringByReplacingMatchesInString( str, options: [], range: NSRange(location: 0, length: str.characters.count), withTemplate: "+" ) // output: "This+is+my+string"
快速扩展:
extension String { func stringByReplacing(replaceStrings set: [String], with: String) -> String { var stringObject = self for string in set { stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with) } return stringObject } }
继续,像let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
函数的速度是我不能引以为豪的,但是你可以一次传递一个String
数组来做多个replace。
这是一个扩展的就地出现replaceString
方法,这不是没有不必要的副本,并做好一切:
extension String { mutating func replaceOccurrences(of target: String, with replacement: String, options: String.CompareOptions = [], locale: Locale? = nil) { var range: Range<String.Index>? repeat { range = self.range(of: source, options: options, range: range.map { $0.lowerBound..<self.endIndex }, locale: locale) if let range = range { self.replaceSubrange(range, with: new) } } while range != nil } }
(方法签名也模仿内置的String.replacingOccurrences()
方法的签名)
可以用以下方式使用:
var string = "this is a string" string.replaceOccurrences(of: " ", with: "_") print(string) // "this_is_a_string"