Split Text into Fixed-Length Chunks
Problem statement
Given a string text and a positive integer k, split the string from left to right into consecutive chunks.
- Every chunk except possibly the last must contain exactly
kcharacters. - If fewer than
kcharacters remain, return them as the last chunk without padding. - Keep every character exactly once and in order. Spaces and punctuation count toward the length; do not split by words or trim whitespace.
- Return an empty array when
textis empty. Do not add an empty trailing chunk when the length is divisible byk.
Function
splitFixedLength(text: String, k: int) → String[]Examples
Example 1
text = "abcdefg"k = 3return = ["abc","def","g"]Two full chunks contain three characters each. The remaining character forms the last chunk.
Example 2
text = "ab cd! "k = 3return = ["ab ","cd!"," "]Spaces and punctuation count as characters and are preserved, including the trailing space.
Example 3
text = ""k = 4return = []There are no characters, so the result contains no chunks.
Constraints
0 <= text.length <= 2000.1 <= k <= 2000.- Every character is printable ASCII, with character code from
32to126.