Answer the question
In order to leave comments, you need to log in
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: " ")
Answer the question
In order to leave comments, you need to log in
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question