ios - 如何在 swift 中每 N 个字符处为字符串添加分隔符?
我有一个包含二进制数字的字符串。如何将它分成一对数字?
假设字符串是:
letx ="11231245"
我想在每 2 个字符后添加一个分隔符,例如“:”(即冒号)。
我希望输出为:
"11:23:12:45"
我怎么能在 Swift 中做到这一点?
最佳答案
Swift 5.2 • Xcode 11.4 或更高版本
extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guardstart else{returnnil}
letend =index(start,offsetBy: maxLength,limitedBy:endIndex) ??endIndex
defer{ start = end }
returnself[start..
}
}
func every(n: Int) -> UnfoldSequence<Element,Index> {
sequence(state: startIndex) { index in
guardindex else{returnnil}
defer{let_ =formIndex(&index,offsetBy: n,limitedBy:endIndex) }
returnself[index]
}
}
var pairs: [SubSequence] { .init(unfoldSubSequences(limitedTo: 2)) }
}
extension StringProtocol where Self: RangeReplaceableCollection {
mutatingfuncinsert(separator: S,everyn:Int) {
forindexinindices.every(n: n).dropFirst().reversed() {
insert(contentsOf: separator,at: index)
}
}
funcinserting(separator: S,everyn:Int) ->Self{
.init(unfoldSubSequences(limitedTo: n).joined(separator: separator))
}
}
测试
letstr ="112312451"letfinal0= str.unfoldSubSequences(limitedTo:2).joined(separator:":")print(final0) //"11:23:12:45:1"letfinal1= str.pairs.joined(separator:":")print(final1) //"11:23:12:45:1"letfinal2= str.inserting(separator:":", every:2)print(final2) //"11:23:12:45:1\n"varstr2="112312451"str2.insert(separator:":", every:2)print(str2) //"11:23:12:45:1\n"varstr3="112312451"str3.insert(separator:":", every:3)print(str3) //"112:312:451\n"varstr4="112312451"str4.insert(separator:":", every:4)print(str4) //"1123:1245:1\n"