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

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

假设字符串是:

let x = "11231245"

我想在每 2 个字符后添加一个分隔符,例如“:”(即冒号)。

我希望输出为:

"11:23:12:45"

我怎么能在 Swift 中做到这一点?

stack overflow How add separator to string at every N characters in swift?
原文答案
author avatar

接受的答案

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:1n"

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

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

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

答案:

作者头像

我会选择这个紧凑的解决方案(在 Swift 4 中):

let s = "11231245"
let r = String(s.enumerated().map { $0 > 0 && $0 % 2 == 0 ? [":", $1] : [$1]}.joined())

您可以进行扩展并参数化步幅和分隔符,以便您可以将它用于您想要的每个值(在我的情况下,我使用它来转储 32 位空格操作的十六进制数据):

extension String {
    func separate(every stride: Int = 4, with separator: Character = " ") -> String {
        return String(enumerated().map { $0 > 0 && $0 % stride == 0 ? [separator, $1] : [$1]}.joined())
    }
}

在您的情况下,这会产生以下结果:

let x = "11231245"
print (x.separate(every:2, with: ":")

$ 11:23:12:45
作者头像

简短而简单,如果需要,添加一个或两个 let

extension String {

    func separate(every: Int, with separator: String) -> String {
        return String(stride(from: 0, to: Array(self).count, by: every).map {
            Array(Array(self)[$0..<min($0 + every, Array(self).count)])
        }.joined(separator: separator))
    }
}

let a = "separatemepleaseandthankyou".separate(every: 4, with: " ")

a

单独收费,请放心,谢谢

作者头像

斯威夫特 5.3

    /// Adds a separator at every N characters
    /// - Parameters:
    ///   - separator: the String value to be inserted, to separate the groups. Default is " " - one space.
    ///   - stride: the number of characters in the group, before a separator is inserted. Default is 4.
    /// - Returns: Returns a String which includes a `separator` String at every `stride` number of characters.
    func separated(by separator: String = " ", stride: Int = 4) -> String {
        return enumerated().map { $0.isMultiple(of: stride) && ($0 != 0) ? "(separator)($1)" : String($1) }.joined()
    }
作者头像

它是我在 swift 4 中的代码

let x = "11231245"

var newText = String()
    for (index, character) in x.enumerated() {
        if index != 0 && index % 2 == 0 {
            newText.append(":")
        }
        newText.append(String(character))
    }
    print(newText)

输出 11:23:12:45

作者头像

我对该代码的尝试是:

func insert(seperator: String, afterEveryXChars: Int, intoString: String) -> String {
    var output = ""
    intoString.characters.enumerate().forEach { index, c in
        if index % afterEveryXChars == 0 && index > 0 {
            output += seperator
        }
        output.append(c)
    }
    return output
}

insert(":", afterEveryXChars: 2, intoString: "11231245")

哪个输出

11:23:12:45

作者头像
let y = String(
    x.characters.enumerate().map() {
        $0.index % 2 == 0 ? [$0.element] : [$0.element, ":"]
    }.flatten()
)
作者头像

Swift 4.2.1 - Xcode 10.1

extension String {

    func insertSeparator(_ separatorString: String, atEvery n: Int) -> String {
        guard 0 < n else { return self }
        return self.enumerated().map({String($0.element) + (($0.offset != self.count - 1 && $0.offset % n ==  n - 1) ? "(separatorString)" : "")}).joined()
    }

    mutating func insertedSeparator(_ separatorString: String, atEvery n: Int) {
        self = insertSeparator(separatorString, atEvery: n)
    }
}

用法

let testString = "11231245"

let test1 = testString.insertSeparator(":", atEvery: 2)
print(test1) // 11:23:12:45

var test2 = testString
test2.insertedSeparator(",", atEvery: 3)
print(test2) // 112,312,45    
作者头像

插入分隔符的简单一行代码(Swift 4.2):-

let testString = "123456789"

let ansTest = testString.enumerated().compactMap({ ($0 > 0) && ($0 % 2 == 0) ? ":($1)" : "($1)" }).joined() ?? ""
print(ansTest) // 12:34:56:78:9
作者头像

我在这里有点晚了,但我喜欢像这样使用正则表达式:

extension String {
    func separating(every: Int, separator: String) -> String {
        let regex = #"(.{#(every)})(?=.)"#
        return self.replacingOccurrences(of: regex, with: "$1(separator)", options: [.regularExpression])
    }
}

"111222333".separating(every: 3, separator: " ")

输出:

"111 222 333"