fork download
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4.  
  5. // Сравнение слов - через указатели на указатели
  6. int wordsCmp(const void* a, const void* b)
  7. {
  8. const char * c = *(const char **)a;
  9. const char * d = *(const char **)b;
  10. return strcmp(c,d);
  11. }
  12.  
  13. char * sortIt(const char * str)
  14. {
  15. // Находим все слова - указатели на них. Их никак не больше половины длины строки.
  16. const char ** words = malloc(sizeof(char*)*strlen(str)/2);
  17. const char * c = str;
  18.  
  19. int idx = 0;
  20. while(*c == ' ') ++c;
  21. words[idx++] = c++;
  22. for(;*c;++c)
  23. if (*c != ' ' && *(c-1) == ' ') words[idx++] = c;
  24.  
  25. // Сортировка массива указателей
  26. qsort((void*)words,idx,sizeof(char*),wordsCmp);
  27.  
  28. // Копия строки (чтоб нужной длины была
  29. char * s = malloc(strlen(str)+1);
  30. char *z = s;
  31. *s = 0;
  32. // Запись слов в новую строку
  33. for(int i = 0; i < idx; ++i)
  34. {
  35. for(const char * t = words[i]; *t && *t != ' ';)
  36. *z++ = *t++;
  37. if (i < idx-1) *z++ = ' ';
  38. }
  39. *z = 0;
  40.  
  41.  
  42. free(words);
  43. return s;
  44. }
  45.  
  46. int main()
  47. {
  48. char str[] = "Sorry I can not write this simple program";
  49. printf("%s\n", str);
  50. char * res = sortIt(str);
  51. printf("%s\n", res);
  52. free(res);
  53. }
  54.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Sorry I can not write this simple program
I Sorry can not program simple this write