Here's a simple strategy to reverse the order of words in a string.
- Reverse the string (sentence)
- Reverse back each word in the string
Let's break down the task into the following functions:
int mystrlen(char *s); // find the length of the string
char *rev_substr(char *s, int len); // reverse the substring s of length len
char *rev_sentence(char *s); // reverse the order of words in the string s
Here are the function definitions:
int mystrlen(char *s) {
int i = 0;
while(*s) {
i++;
s++;
}
return i;
}
char *rev_substr(char *s, int len) {
int i = 0;
int j = len - 1;
char temp;
while(i < j) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
return s;
}
char *rev_sentence(char *s) {
int i, j = 0;
int len = mystrlen(s);
rev_substr(s, len); // reverse the whole string
for(i = 0; i <= len; i++) {
// a word is delimited by a space or the null character
if(s[i] == ' ' || s[i] == '\0') {
rev_substr(s+j, i-j); // reverse back each word
j = i + 1; // j is the index of the first letter of the next word
}
}
return s;
}
A sample implementation:
int main(void) {
char s[] = "this is a test";
printf("%s\n", rev_sentence(s));
return 0;
}