Answers:
此答案已针对Swift 4和5进行了更新。如果您仍在使用Swift 1、2或3,请参阅修订历史记录。
您有两种选择。您可以按照@jaumard的建议进行操作并使用replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
就像下面@cprcrack所指出的那样,options
and range
参数是可选的,因此,如果您不想指定字符串比较选项或范围以在其中进行替换,则只需执行以下操作。
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
或者,如果数据采用特定格式,例如您要替换的分隔字符,则可以使用components()
将字符串拆分为and数组,然后可以使用join()
函数将其与指定的分隔符放回原处。
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
或者,如果您正在寻找一种不使用NSString API的更快速的解决方案,则可以使用它。
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
"x86_64"
新映射看起来就像"Optional([\"x\", \"8\", \"6\", \"_\", \"6\", \"4\"])"
stringByReplacingOccurrencesOfString
在Swift 2中使用存在问题的人,您都需要import Foundation
能够使用该方法。
您可以使用此:
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 3,Swift 4,Swift 5解决方案
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: "+")
我正在使用此扩展名:
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:"+")
与Sunkas类似的Swift 3解决方案:
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
{
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解决方案:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
根据Swift 3命名约定尝试提供合适的函数名称。
发生在我身上的事情较少,我只想在其中更改(单词或字符) String
所以我用 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
}
}
用法
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
replace
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
replacingOccurrences
在String
?
我认为Regex是最灵活和可靠的方式:
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
以进行多个替换。
这是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
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"
如果您不想使用Objective-C NSString
方法,则可以使用split
和join
:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " })
返回一个字符串数组(["This", "is", "my", "string"]
)。
join
将这些元素与相连+
,得到所需的输出:"This+is+my+string"
。
这是上就地发生替换方法的扩展,该方法String
没有不必要的副本,并就地进行了所有操作:
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"