我正在寻找一种方法来替换Swift中的字符
例如:"This is my string"
我想将" "替换为"+",以便得到"This+is+my+string"。
我该如何实现?
String
。例如:"This is my string"
我想将" "替换为"+",以便得到"This+is+my+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
即可。 - WestCoastProjectsvar str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
String
中找不到 replacingOccurrences
方法? - WestCoastProjectsXcode 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"
String
不再符合SequenceType
。换句话说,您不能使用for...in
循环遍历字符串。String
转换为Array
,以便像这样获得索引的好处:let input = Array(str)
我记得曾经试图在没有进行任何转换的情况下对String
进行索引。我非常沮丧,无法得到所需的结果,差点放弃。
但最终,我想出了自己的解决方案,并在此提供完整代码:
extension String {
subscript (_ index: Int) -> String {
get {
String(self[self.index(startIndex, offsetBy: index)])
}
set {
remove(at: self.index(self.startIndex, offsetBy: index))
insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
}
}
}
现在你可以像最初想要的那样,使用字符串的索引读取和替换一个单个字符:
var str = "cat"
for i in 0..<str.count {
if str[i] == "c" {
str[i] = "h"
}
}
print(str)
这是一种简单而实用的方法来使用并通过Swift的字符串访问模型。
现在,当您可以直接循环遍历字符串时,就不需要将其转换为Array
了,您会感到一帆风顺。
试试它,看看它是否有帮助!
replacingOccurrences(of: " ", with: "_")
进行替换即可。var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
RangeReplaceableCollection
上使用新方法{{link1:replace(_:with:maxReplacements:)
}},该方法将Regex
作为参数,我们可以自定义请求。var myString = "This is my string"
myString.replace(" ", with: "+")
但不要忘记 import RegexBuilder
以启用此功能
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
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"
Swift扩展:
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
数组来进行多个替换。