Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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 117 views
1 answer 169 views
1 answer 111 views
1 answer 121 views
1 answer 114 views
...