本人親測有效堕仔!更多交流可以家魏鑫:lixiaowu1129躲因,公重好:iOS過審匯總蔑祟,一起探討iOS技術(shù)趁耗!
我有以雙引號開頭和結(jié)尾的Swift字符串。它們內(nèi)部也包含雙引號疆虚。內(nèi)部雙引號是一對(第一個示例)苛败,除非the是雙引號之前的最后一個字符(第二個示例):
"-5 -5"" -Animated -Cartoon",我需要成為-5 -5" -Animated -Cartoon
或
"-POTF -Force -12 -12""径簿,我需要成為-POTF -Force -12 -12"
我需要一種刪除外部雙引號并將“內(nèi)部”雙引號設(shè)置為僅一個雙引號的方法罢屈。 在Kotlin中,我可以執(zhí)行以下操作:使用removeSurrounding(請參閱以下定義)篇亭,然后將2雙引號替換為1
removeSurrounding
在且僅在以分隔符開頭和結(jié)尾為的情況下缠捌,才從該字符串的開頭和結(jié)尾刪除給定的分隔符字符串。否則译蒂,返回此字符串不變曼月。
newString = string.removeSurrounding("\"").replace("\"\"","\"")
解決方法:
您可以創(chuàng)建自己的擴展StringProtocol的字符串removeSurrounding方法肃叶,您只需要檢查原始字符串是否以特定字符開頭和結(jié)尾,并返回原始字符串并刪除第一個和最后一個字符即可十嘿,否則返回不變:
extension StringProtocol {
/// Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.
func removingSurrounding(_ character: Character) -> SubSequence {
guard count > 1,first == character,last == character else {
return self[...]
}
return dropFirst().dropLast()
}
}
要創(chuàng)建同一方法的變異版本因惭,您只需要將對RangeReplaceableCollectionn的擴展約束為將您的方法聲明為變異,并使用變異方法removeFirst和removeLast而不是dropFirst和dropLast:
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func removeSurrounding(_ character: Character) {
guard count > 1,last == character else {
return
}
removeFirst()
removeLast()
}
}
舉個??:
let string1 = #""-5 -5"" -Animated -Cartoon""#
let string2 = #""-POTF -Force -12 -12"""#
let newstring1 = string1.removingSurrounding("\"").replacingOccurrences(of: "\"\"",with: "\"") // "-5 -5" -Animated -Cartoon"
let newstring2 = string2.removingSurrounding("\"").replacingOccurrences(of: "\"\"",with: "\"") // "-POTF -Force -12 -12""
效果圖如下:
本文由mdnice多平臺發(fā)布