fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. // Helper function to reverse a single word
  5. void reverse_word(char *word, int len)
  6. {
  7. for (int i = 0, j = len - 1; i < j; i++, j--) {
  8. char tmp = word[i];
  9. word[i] = word[j];
  10. word[j] = tmp;
  11. }
  12. }
  13.  
  14. char * reverse_line(char *line)
  15. {
  16. int word_start = 0; // This marks the index of the first letter of a word
  17.  
  18. // The loop needs to include the null-terminator '\0'
  19. for (int i = 0; i == 0 || line[i-1] != '\0'; i++) {
  20. // Search for non-letters
  21. if (!isalpha(line[i])) {
  22. // Do the in-place reversal of the word
  23. reverse_word(&line[word_start], i - word_start);
  24. // Update for next word
  25. word_start = i + 1;
  26. }
  27. }
  28. return line;
  29. }
  30.  
  31. int main(void)
  32. {
  33. char s[] = "Simon liebt Pizza!";
  34. printf("%s\n", s);
  35. printf("%s\n", reverse_line(s));
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 4496KB
stdin
Standard input is empty
stdout
Simon liebt Pizza!
nomiS tbeil azziP!