Skip to content

Instantly share code, notes, and snippets.

@shiblisec
Last active October 31, 2018 12:16
Show Gist options
  • Save shiblisec/df12208ac8913764e47798cebf511bee to your computer and use it in GitHub Desktop.
Save shiblisec/df12208ac8913764e47798cebf511bee to your computer and use it in GitHub Desktop.
C program to reverse the order of words in a String.
#include<stdio.h>
#include<string.h>
char *reverse(char str[]){
static char result[100];
int start, end, i, j=0;
int len = strlen(str) - 1;
start = end = i = len; //starting from the end of the string.
while(i >= 0){
if(str[i] == ' '){
start = i + 1;
while(start < end){
result[j] = str[start++];
j++;
}
result[j] = ' ';
start = end = i;
j++;
}
i--;
}
//adding the last word to the string.
start = 0;
while(start != end){
result[j] = str[start];
j++;
start++;
}
return result;
}
int main(){
char str[100];
printf("Enter a string: ");
fgets(str,100,stdin); //fgets add a \n character at the end of the string by default
printf("The reverse order string is: %s\n", reverse(str));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment