fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX_WORDS 10
  6.  
  7. #define TEST(s) { \
  8.   char *str = make_string(s); \
  9.   puts(str); \
  10.   free(str); \
  11. }
  12.  
  13. static size_t words_count = 0;
  14. static const char *words[MAX_WORDS] = { 0 };
  15.  
  16. int cmp_str(const void *p1, const void *p2)
  17. { return strlen(*(const char **) p1) < strlen(*(const char **) p2); }
  18.  
  19. void add_word(const char *word)
  20. {
  21. if (words_count < MAX_WORDS)
  22. words[words_count++] = word;
  23. else {
  24. puts("error: too much words!");
  25. exit(1);
  26. }
  27. }
  28.  
  29. char *get_word(char *str)
  30. {
  31. char *ret;
  32.  
  33. if (str == NULL || *str == 0)
  34. return NULL;
  35.  
  36. while (*str && !isalpha(*str))
  37. ++str;
  38.  
  39. ret = str;
  40.  
  41. while (*str && isalpha(*str))
  42. ++str;
  43. *str = 0;
  44.  
  45. return *ret ? ret : NULL;
  46. }
  47.  
  48. char *make_string(const char *source_str)
  49. {
  50. size_t i;
  51. char *ret;
  52. char *word;
  53. char *str;
  54.  
  55. words_count = 0;
  56. str = alloca(strlen(source_str) + 2);
  57. strcpy(str, source_str);
  58. str[strlen(source_str) + 1] = 0;
  59.  
  60. while ((word = get_word(str)) != NULL) {
  61. add_word(word);
  62. str = word + strlen(word) + 1;
  63. }
  64.  
  65. qsort(words, words_count, sizeof(char *), cmp_str);
  66.  
  67. ret = calloc(strlen(source_str) + 1, 1);
  68. for (i = 0; i < words_count; i++) {
  69. strcat(ret, words[i]);
  70.  
  71. if (i != words_count - 1)
  72. strcat(ret, " ");
  73. }
  74.  
  75. return ret;
  76. }
  77.  
  78. int main()
  79. {
  80. TEST("hello");
  81. TEST(" hell, world ");
  82. TEST(" my other car is cdr ");
  83. TEST(" the quick brown fox, jumps over the, lazy dog ");
  84. return 0;
  85. }
  86.  
Success #stdin #stdout 0.01s 1808KB
stdin
Standard input is empty
stdout
hello
world hell
other car cdr my is
quick brown jumps over lazy the fox the dog