How to split a string into chunks of two characters each in Swift

1 Answer

0 votes
import Foundation

func splitStringIntoChunks(_ str: String, chunkSize: Int) -> [String] {
    var chunks: [String] = []
    let length = str.count

    for i in stride(from: 0, to: length, by: chunkSize) {
        let startIndex = str.index(str.startIndex, offsetBy: i)
        let endIndex = str.index(startIndex, offsetBy: chunkSize, limitedBy: str.endIndex) ?? str.endIndex
        chunks.append(String(str[startIndex..<endIndex]))
    }

    return chunks
}

let str = "abcdefghijk"
let chunkSize = 2

let chunks = splitStringIntoChunks(str, chunkSize: chunkSize) 

print("Chunks of two characters:")
for chunk in chunks {
    print(chunk)
}


 
 
/*
run:

Chunks of two characters:
ab
cd
ef
gh
ij
k
 
*/

 



answered Mar 30, 2025 by avibootz
...