Skip to content

Instantly share code, notes, and snippets.

@vo
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vo/8995789 to your computer and use it in GitHub Desktop.
Save vo/8995789 to your computer and use it in GitHub Desktop.
Reverse order of words in string in C
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "hello world!";
int n = strlen(s);
// reverse string in-place.
int i, j, t;
for(i=0, j=n-1; i<j; ++i, --j) {
char c = s[i];
s[i] = s[j];
s[j] = c;
}
printf("%s\n", s);
// reverse words, in place.
for(i=0, j=0; i < n; i=j) {
while(j < n && s[j] != ' ') j++;
for(t=j-1; i<t; ++i, --t) {
char c = s[i];
s[i] = s[t];
s[t] = c;
}
while(j < n && s[j] == ' ') j++;
}
printf("%s\n", s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment