gpt4 book ai didi

swift - 字符串替换没有 NSString API 的子字符串

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:27 24 4
gpt4 key购买 nike

我希望能够在不桥接到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com