Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- size_t word_num(char *phrase, int length) {
- int words = 0;
- for (int i = 0; i < length; i++) {
- if (phrase[i] == ' ' || phrase[i] == '\0') {
- words++;
- }
- }
- return words;
- }
- int main() {
- char phrase[] = "andiamo a fare le botte";
- int phrase_length = sizeof(phrase) / sizeof(phrase[0]);
- int words = word_num(phrase, phrase_length);
- char **word_list = (char**)malloc(words * sizeof(char*));
- int word_ind = 0;
- int letter_ind = 0;
- for (int i = 0; i < phrase_length; i++) {
- if (phrase[i] != ' ' && phrase[i] != '\0') {
- if (letter_ind == 0) {
- word_list[word_ind] = (char*)malloc(phrase_length);
- }
- word_list[word_ind][letter_ind] = phrase[i];
- letter_ind++;
- } else {
- word_list[word_ind][letter_ind] = '\0';
- word_list[word_ind] = (char*)realloc(word_list[word_ind], letter_ind + 1);
- word_ind++;
- letter_ind = 0;
- }
- }
- for (int w = 0; w < words; w++) {
- printf("%s ", word_list[w]);
- free(word_list[w]);
- }
- free(word_list);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement