我希望能够在不桥接到 NS 类的情况下查找和替换 native Swift 字符串中出现的子字符串。我怎样才能做到这一点?
这不是 this question 的副本,因为这个问题是关于替换单个字符的。这道题是关于查找和替换一个可能包含很多字符的子串。
最佳答案
没有基础
的方法:
extension String {
func replacing(_ oldString: String, with newString: String) -> String {
guard !oldString.isEmpty, !newString.isEmpty else { return self }
let charArray = Array(self.characters)
let oldCharArray = Array(oldString.characters)
let newCharArray = Array(newString.characters)
var matchedChars = 0
var resultCharArray = [Character]()
for char in charArray {
if char == oldCharArray[matchedChars] {
matchedChars += 1
if matchedChars == oldCharArray.count {
resultCharArray.append(contentsOf: newCharArray)
matchedChars = 0
}
} else {
for i in 0 ..< matchedChars {
resultCharArray.append(oldCharArray[i])
}
if char == oldCharArray[0] {
matchedChars = 1
} else {
matchedChars = 0
resultCharArray.append(char)
}
}
}
return String(resultCharArray)
}
}
示例用法:
let myString = "Hello World HelHelloello Hello HellHellooo"
print(myString.replacing("Hello", with: "Hi"))
输出:
Hi World HelHiello Hi HellHioo
使用Foundation
的方法:
您可以在 String
结构上使用 replacingOccurrences
方法。
let myString = "Hello World"
let newString = myString.replacingOccurrences(of: "World", with: "Everyone")
print(newString) // prints "Hello Everyone"
关于swift - 字符串替换没有 NSString API 的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825979/