Advertisement
Luca8

Untitled

Oct 16th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. size_t word_num(char *phrase, int length) {
  5.     int words = 0;
  6.  
  7.     for (int i = 0; i < length; i++) {
  8.         if (phrase[i] == ' ' || phrase[i] == '\0') {
  9.             words++;
  10.         }
  11.     }
  12.  
  13.     return words;
  14. }
  15.  
  16. int main() {
  17.     char phrase[] = "andiamo a fare le botte";
  18.     int phrase_length = sizeof(phrase) / sizeof(phrase[0]);
  19.  
  20.     int words = word_num(phrase, phrase_length);
  21.     char **word_list = (char**)malloc(words * sizeof(char*));
  22.  
  23.     int word_ind = 0;
  24.     int letter_ind = 0;
  25.  
  26.     for (int i = 0; i < phrase_length; i++) {
  27.         if (phrase[i] != ' ' && phrase[i] != '\0') {
  28.             if (letter_ind == 0) {
  29.                 word_list[word_ind] = (char*)malloc(phrase_length);
  30.             }
  31.             word_list[word_ind][letter_ind] = phrase[i];
  32.             letter_ind++;
  33.         } else {
  34.             word_list[word_ind][letter_ind] = '\0';
  35.             word_list[word_ind] = (char*)realloc(word_list[word_ind], letter_ind + 1);
  36.             word_ind++;
  37.             letter_ind = 0;
  38.         }
  39.     }
  40.  
  41.     for (int w = 0; w < words; w++) {
  42.         printf("%s ", word_list[w]);
  43.         free(word_list[w]);
  44.     }
  45.  
  46.     free(word_list);
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement