How to split a string of total divisible by 3 words into 3-word lines of text in C

1 Answer

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

char** split_string_into_3_word_lines(char* str) {
    char** words = malloc(sizeof(char*) * 99);
    
    int word_count = 0;
    char* word = strtok(str, " ");
    while (word != NULL) {
        words[word_count++] = word;
        word = strtok(NULL, " ");
    }

    int line_count = 3;
    char** lines = malloc(sizeof(char*) * line_count);

    for (int i = 0; i < line_count; i++) {
        lines[i] = malloc(sizeof(char) * 64);
        // 0 1 2 // 3 4 5 // 6 7 8
        snprintf(lines[i], 64, "%s %s %s", words[i * 3], words[i * 3 + 1], words[i * 3 + 2]); 
    }

    free(words);

    return lines;
}

int main() {
    char str[] = "java c c++ python rust go php typescript c#";

    char** lines = split_string_into_3_word_lines(str);

    for (int i = 0; i < 3; i++) {
        printf("%s\n", lines[i]);
        free(lines[i]);
    }

    free(lines);

    return 0;
}





/*
run:

java c c++
python rust go
php typescript c#

*/

 



answered May 23, 2024 by avibootz

Related questions

1 answer 101 views
1 answer 136 views
1 answer 101 views
1 answer 110 views
1 answer 99 views
...