Last active
August 29, 2015 13:56
-
-
Save vo/8995789 to your computer and use it in GitHub Desktop.
Reverse order of words in string in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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