fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void reverse(char*, int);
  5.  
  6. int main(int argc, char **argv)
  7. {
  8. char st[]= "hello world";
  9. int len = strlen(st);
  10. int i=0,j=0;
  11.  
  12. reverse(st,len-1); // Reverse the entire string. hello world => dlrow olleh
  13.  
  14. while(st[j]){ //Loop till the string ends
  15. if (*(st+j)==' ') { //if you hit a blank space
  16. reverse(st+i,j-i-1); // reverse the string starting at position i till position j
  17. i=++j; //new i & j are 1 position to the right of old j
  18. }
  19. else {
  20. j++; //if a chacacter is found, move to next position
  21. }
  22. }
  23. reverse(st+i,j-i-1); // reverse the last word of the string
  24.  
  25. printf("%s",st);
  26. return 0;
  27. }
  28.  
  29. void reverse(char *s, int n)
  30. {
  31. char *end = s+n; //end is a pointer to an address which is n addresses from the starting address
  32. char tmp;
  33. while (end>s) //perform swap
  34. {
  35. tmp = *end;
  36. *end = *s;
  37. *s = tmp;
  38. end--;
  39. s++;
  40. }
  41. }
Success #stdin #stdout 0.02s 1676KB
stdin
Standard input is empty
stdout
world hello