Last active
October 31, 2018 12:16
-
-
Save shiblisec/df12208ac8913764e47798cebf511bee to your computer and use it in GitHub Desktop.
C program to reverse the order of words in a String.
This file contains hidden or 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> | |
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