C program to reverse the string word by word
The following C program will reverse the string word by word
Example:
If the input is : Have a nice day
Output will be:day nice a Have
Example:
If the input is : Have a nice day
Output will be:day nice a Have
#include#include void swap(char *string, int length) { int i; char ch; for (i = 0; i < length/2; i++) { ch = string[length-i-1]; string[length-1-i]=string[i]; string[i]=ch; } } char *reverse(char *string) { int length = strlen(string); char ch; int i, prev_index; /* * The following for loop for swap the character to character */ for ( i = 0 ; i < length/2; i++) { ch = string[length-1-i]; string[length-1-i] = string[i]; string[i] = ch; } /* * Next for loop we have to swap word by word */ i = 0; while (string[i] !='\0') { prev_index = i; while (string[i] != ' ' && string[i] != '\0') i++; swap(string+prev_index,i - prev_index); if(string[i] == ' ') i++; } return string; } int main(int argc, char *argv[]) { char str[100]; printf("Enter the string:\n"); scanf("%[^\n]",str); printf("string before reverse:%s\n",str); printf("string in reverse order:%s\n",reverse(str)); }
Comments
Post a Comment