Created
December 4, 2024 21:35
-
-
Save robertmryan/d7eadeec08b573c5add9727645897e0e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension StringProtocol { | |
func split(into length: Int) -> [SubSequence] { | |
let count = self.count | |
return stride(from: 0, to: count, by: length).map { i in | |
let start = index(startIndex, offsetBy: i) | |
let end = index(startIndex, offsetBy: Swift.min(i + length, count)) | |
return self[start ..< end] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While I tried to make this generic, using
StringProtocol
, to supportSubstring
, we could make this even a little more generic, to split anyCollection
type intoSubSequence
s of a certain length. Admittedly, this is not immediately relevant to the question of “how do I split strings into substrings with a maximum length”, but just an academic observation:Or, technically, this might be more efficient: