我想编写一个可以像这样使用的函数:
let = "".replacingFirstOccurrence(of: "", with: "")
鉴于how odd both this string and Swift's String
library are,这在Swift中是否可行?
答案 0 :(得分:11)
根据Why are emoji characters like ???? treated so strangely in Swift strings?获得的见解,一种明智的方法可能是取代Unicode标量:
extension String {
func replacingFirstOccurrence(of target: UnicodeScalar, with replacement: UnicodeScalar) -> String {
let uc = self.unicodeScalars
guard let idx = uc.index(of: target) else { return self }
let prefix = uc[uc.startIndex..<idx]
let suffix = uc[uc.index(after: idx) ..< uc.endIndex]
return "\(prefix)\(replacement)\(suffix)"
}
}
示例:
let family1 = ""
print(family1.characters.map { Array(String($0).unicodeScalars) })
// [["\u{0001F469}", "\u{200D}"], ["\u{0001F469}", "\u{200D}"], ["\u{0001F467}", "\u{200D}"], ["\u{0001F466}"]]
let family2 = family1.replacingFirstOccurrence(of: "", with: "")
print(family2) //
print(family2.characters.map { Array(String($0).unicodeScalars) })
// [["\u{0001F469}", "\u{200D}"], ["\u{0001F469}", "\u{200D}"], ["\u{0001F466}", "\u{200D}"], ["\u{0001F466}"]]
这是一个可能的版本,它定位并替换任意字符串的Unicode标量:
extension String {
func replacingFirstOccurrence(of target: String, with replacement: String) -> String {
let uc = self.unicodeScalars
let tuc = target.unicodeScalars
// Target empty or too long:
if tuc.count == 0 || tuc.count > uc.count {
return self
}
// Current search position:
var pos = uc.startIndex
// Last possible position of `tuc` within `uc`:
let end = uc.index(uc.endIndex, offsetBy: tuc.count - 1)
// Locate first Unicode scalar
while let from = uc[pos..<end].index(of: tuc.first!) {
// Compare all Unicode scalars:
let to = uc.index(from, offsetBy: tuc.count)
if !zip(uc[from..<to], tuc).contains(where: { $0 != $1 }) {
let prefix = uc[uc.startIndex..<from]
let suffix = uc[to ..< uc.endIndex]
return "\(prefix)\(replacement)\(suffix)"
}
// Next search position:
uc.formIndex(after: &pos)
}
// Target not found.
return self
}
}
答案 1 :(得分:7)
使用range(of:options:range:locale:)
解决方案变得非常简洁:
extension String {
func replaceFirstOccurrence(of searchString: String, with replacementString: String) -> String {
guard let range = self.range(of: searchString, options: .literal) else { return self }
return self.replacingCharacters(in: range, with: replacementString)
}
}
首先在实例中找到searchString
的范围,如果找到范围,则范围将替换为replacementString
。否则,实例只返回自身。并且,由于range(of:)
方法在找到匹配后立即返回,因此保证返回的范围是第一次出现。
"221".replaceFirstOccurrence(of: "2", with: "3") // 321
"".replaceFirstOccurrence(of: "\u{1f469}", with: "\u{1f468}") //
*为了澄清,最后一个测试案例将女人 - 女人 - 女孩 - 男孩转换为男女女孩。 < / p>