fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. // step 1. reverse the target sequence
  6. // "abc 123 xyz" ==> "cba 123 xyz"
  7. // ^^^ ^^^
  8.  
  9. // step 2. Reverse the entire sequence
  10. // "cba 123 xyz" ==> "zyx 321 abc"
  11.  
  12. // step 3 Reverse the non-target sequence, not including the trailing space
  13. // "zyx 321 abc " => "123 xyz abc"
  14. // ^^^^^^^ ^^^^^^^
  15. //
  16. // repeat this (recursion or iteration, makes no difference) for
  17. // the non-target segment, adjusting the end-marker to do so.
  18.  
  19. void reverse_letters(char *beg, char *end)
  20. {
  21. while (beg < --end)
  22. {
  23. char tmp = *beg;
  24. *beg++ = *end;
  25. *end = tmp;
  26. }
  27. }
  28.  
  29. char *reverse_words(char *beg, char *end)
  30. {
  31. // find whitespace. if none then we're done.
  32. char *p = beg;
  33. for (; p != end && !isspace((unsigned char)*p); ++p);
  34.  
  35. if (p != end)
  36. {
  37. reverse_letters(beg, p);
  38. reverse_letters(beg, end);
  39. reverse_letters(beg, beg + (end - p - 1));
  40. reverse_words(beg, beg + (end - p - 1));
  41. }
  42.  
  43. return beg;
  44. }
  45.  
  46. int main()
  47. {
  48. char words[] = "abc 123 xyz";
  49. reverse_words(words, words + strlen(words));
  50. puts(words);
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0s 4512KB
stdin
Standard input is empty
stdout
xyz 123 abc