gpt4 book ai didi

ios - 如何在 swift 中每 N 个字符处为字符串添加分隔符?

转载 作者:IT王子 更新时间:2023-10-29 05:08:41 24 4
gpt4 key购买 nike

我有一个包含二进制数字的字符串。如何将它分成一对数字?

假设字符串是:

let x = "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
guard start < endIndex else { return nil }
let end = index(start, offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
defer { start = end }
return self[start..<end]
}
}

func every(n: Int) -> UnfoldSequence<Element,Index> {
sequence(state: startIndex) { index in
guard index < endIndex else { return nil }
defer { let _ = formIndex(&index, offsetBy: n, limitedBy: endIndex) }
return self[index]
}
}

var pairs: [SubSequence] { .init(unfoldSubSequences(limitedTo: 2)) }
}

extension StringProtocol where Self: RangeReplaceableCollection {

mutating func insert<S: StringProtocol>(separator: S, every n: Int) {
for index in indices.every(n: n).dropFirst().reversed() {
insert(contentsOf: separator, at: index)
}
}

func inserting<S: StringProtocol>(separator: S, every n: Int) -> Self {
.init(unfoldSubSequences(limitedTo: n).joined(separator: separator))
}
}

测试

let str = "112312451"

let final0 = str.unfoldSubSequences(limitedTo: 2).joined(separator: ":")
print(final0) // "11:23:12:45:1"

let final1 = str.pairs.joined(separator: ":")
print(final1) // "11:23:12:45:1"

let final2 = str.inserting(separator: ":", every: 2)
print(final2) // "11:23:12:45:1\n"

var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2) // "11:23:12:45:1\n"

var str3 = "112312451"
str3.insert(separator: ":", every: 3)
print(str3) // "112:312:451\n"

var str4 = "112312451"
str4.insert(separator: ":", every: 4)
print(str4) // "1123:1245:1\n"

关于ios - 如何在 swift 中每 N 个字符处为字符串添加分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454532/

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