I
I
Igor2021-05-11 14:35:56
Swift
Igor, 2021-05-11 14:35:56

How to split a string into an array of strings with a specific length?

Task: There is a string with an arbitrary length, consisting of numbers. It is

necessary to divide this string into an array of substrings, indicating the length of these substrings
"123456789" (the length of the substring is 4) -> ["1234", "5678", "9"]

I came up with this solution:

var str = "123456789"
let sz = 4
for chunk in stride(from: sz, to: str.count, by: sz).reversed() {
    str.insert(" ", at: str.index(str.startIndex, offsetBy: chunk))
}
let chunksOfString = str.components(separatedBy: " ")


Question: is it possible to somehow break a string into an array of substrings with a certain length in a less barbaric way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergei Nazarenko, 2021-05-11
@Lexemz

extension String {
    func components(withLength length: Int) -> [String] {
        return stride(from:0, to: self.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return String(self[start ..< end])
        }
    }
}

let str = "123456789"
let comp1 = str.components(withLength: 4)
let comp2 = str.components(withLength: 3)

dump(comp1)
dump(comp2)

Exhaust609a7c8be66d9151130787.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question