Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include "tested_declarations.h"
- #include "rdebug.h"
- int count_words(const char* ptr)
- {
- int i = 0, counter = 0;
- for(i = 0; *(ptr+i) != '\0'; ++i)
- {
- if( (*(ptr+i)>='A' && *(ptr+i)<='Z') || (*(ptr+i)>='a' && *(ptr+i)<='z') ) {
- if( !((*(ptr+i+1)>='a' && *(ptr+i+1)<='z')|| (*(ptr+i+1)>='A' && *(ptr+i+1)<='Z'))) {
- counter += 1;
- }
- }
- }
- return counter;
- }
- void destroy(char **words)
- {
- if(words == NULL) return ;
- int i=0;
- while(*(words+i)!=NULL)
- {
- free(*(words+i));
- i++;
- }
- free(words);
- }
- char **split_words(const char *text)
- {
- int size = count_words(text);
- char** ptr = (char **)malloc(sizeof(char *)*(size+1));
- if(!ptr) return NULL;
- if(size == 0) { free(ptr); return NULL; }
- int counter = 0, counter2 = 0, counter3 = 0;
- int i = 0, j = 0;
- for(i = 0; *(text+i) != '\0'; i++)
- {
- if((*(text+i)>='a' && *(text+i)<='z')|| (*(text+i)>='A' && *(text+i)<='Z')) {
- if(!((*(text+i+1)>='a' && *(text+i+1)<='z')|| (*(text+i+1)>='A' && *(text+i+1)<='Z'))) {
- *(ptr+counter)=(char *)malloc(sizeof(char)*(counter2+2));
- if(!(*(ptr+counter))) {
- j = 0;
- while(j < counter) { free(*(ptr+j)); j++; }
- free(ptr);
- return NULL;
- }
- counter++;
- counter2=0;
- }
- else counter2++;
- }
- }
- *(ptr+counter)=NULL;
- for(i = 0, counter = 0; *(text+i) != '\0' ; i++)
- {
- if((*(text+i)>='a' && *(text+i)<='z')|| (*(text+i)>='A' && *(text+i)<='Z'))
- {
- *(*(ptr+counter)+counter3)=*(text+i);
- if( !((*(text+i+1)>='a' && *(text+i+1)<='z')|| (*(text+i+1)>='A' && *(text+i+1)<='Z')))
- {
- *(*(ptr+counter)+counter3+1)='\0';
- counter++;
- counter3=0;
- }
- else counter3++;
- }
- }
- return ptr;
- }
- void swap(char **a, char **b)
- {
- char* temp;
- temp = *a;
- *a = *b;
- *b = temp;
- }
- int sort_words(char **words)
- {
- if(!words || !(*words)) return 1;
- for(int i = 0; *(words+i); ++i)
- {
- for(int j = 0; *(words+j+1); ++j)
- {
- if(strcmp(*(words+j),*(words+j+1)) > 0 ) {
- swap((words+j), (words+j+1));
- }
- }
- }
- return 0;
- }
- void show(char ** text)
- {
- while(*text != NULL) {
- printf("%s \n",*text);
- text++;
- }
- }
- int main()
- {
- int var = 0;
- char* ptxt = (char *)malloc(sizeof(char)*1000);
- if(!ptxt) { printf("Failed to allocate memory"); return 8; }
- printf("Enter: ");
- fgets(ptxt, 1000, stdin);
- for(int i = 0; *(ptxt+i) != '\0'; i++) {
- if((*(ptxt+i)>='A' && *(ptxt+i)<='Z') || (*(ptxt+i)>='a' && *(ptxt+i)<='z')) var++;
- }
- if(var==0) { printf("Nothing to show"); free(ptxt); return 0; }
- char ** ptr_ret = split_words(ptxt);
- if(!ptr_ret) { free(ptxt); printf("Failed to allocate memory"); return 8; }
- sort_words(ptr_ret);
- show(ptr_ret);
- free(ptxt);
- destroy(ptr_ret);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement