How add separator to string at every N characters in swift?

3 Solutions Collect From Internet About “How add separator to string at every N characters in swift?”

You can use stride(from:, to:, by:) to iterate every 2 characters in your string and just use join(with: separator) to concatenate your string again.

extension String {
    var pairs: [String] {
        var result: [String] = []
        let characters = Array(self.characters)
        stride(from: 0, to: characters.count, by: 2).forEach {
            result.append(String(characters[$0..<min($0+2, characters.count)]))
        }
        return result
    }
    mutating func insert(separator: String, every n: Int) {
        self = inserting(separator: separator, every: n)
    }
    func inserting(separator: String, every n: Int) -> String {
        var result: String = ""
        let characters = Array(self.characters)
        stride(from: 0, to: characters.count, by: n).forEach {
            result += String(characters[$0..<min($0+n, characters.count)])
            if $0+n < characters.count {
                result += separator
            }
        }
        return result
    }
}

Testing

let str1 = "112312451"

let finalString1 = str1.pairs.joined(separator: ":")   // "11:23:12:45:1"
print(str1)   // "112312451\n"

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


var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2)   // "11:23:12:45:1\n"
let y = String(
    x.characters.enumerate().map() {
        $0.index % 2 == 0 ? [$0.element] : [$0.element, ":"]
    }.flatten()
)

My attempt at that code would be:

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")

Which outputs

11:23:12:45