我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
我正在寻找一种方法来取代字符在一个Swift字符串。
示例:“This is my string”
我想用“+”替换“”以获得“This+is+my+string”。
我怎样才能做到这一点呢?
当前回答
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
输出是
This+is+my+string
其他回答
很少发生在我身上,我只是想改变字符串中的(一个单词或字符)
所以我用了字典
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
基于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的命名约定,提出一个合适的函数名。
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所指出的,选项和范围参数是可选的,所以如果您不想指定字符串比较选项或执行替换的范围,您只需要以下内容。
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
或者,如果数据是这样的特定格式,其中只是替换分隔符,则可以使用components()将字符串拆分为一个数组,然后可以使用join()函数将它们与指定的分隔符组合在一起。
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
或者如果你正在寻找一个更Swifty的解决方案,不利用NSString的API,你可以使用这个。
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
下面是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")进行替换
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)