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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** splitStringIntoChunks(const char* str, size_t chunkSize, size_t* chunkCount) {
    size_t length = strlen(str);
    *chunkCount = (length + chunkSize - 1) / chunkSize; // Calculate the number of chunks

    // Allocate memory for the array of chunks
    char** chunks = (char**)malloc(*chunkCount * sizeof(char*));
    if (!chunks) {
        perror("Memory allocation failed");
        exit(EXIT_FAILURE);
    }

    for (size_t i = 0; i < *chunkCount; i++) {
        // Allocate memory for each chunk
        chunks[i] = (char*)malloc(chunkSize + 1);
        if (!chunks[i]) {
            perror("Memory allocation failed");
            exit(EXIT_FAILURE);
        }

        // Copy the chunk of size `chunkSize` from the str string
        strncpy(chunks[i], &str[i * chunkSize], chunkSize);
        chunks[i][chunkSize] = '\0'; // Null-terminate the chunk
    }

    return chunks;
}

int main() {
    const char* str = "abcdefghijk";
    size_t chunkSize = 2;
    size_t chunkCount;

    char** chunks = splitStringIntoChunks(str, chunkSize, &chunkCount);

    printf("Chunks of two characters:\n");
    for (size_t i = 0; i < chunkCount; i++) {
        printf("%s\n", chunks[i]);
        free(chunks[i]); // Free each chunk
    }
    free(chunks); // Free the array of chunks

    return 0;
}

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

*/

 



answered Mar 30, 2025 by avibootz
edited Mar 30, 2025 by avibootz
...