C Program to reverse the words present in the string.
#include <stdio.h> #include<string.h> void reverse(char*); void rev_words(char*); int main() { char string[40],*b; printf("Enter the string:\n"); scanf("%[^\n]%*c",string); b=string; reverse(b); rev_words(b); printf("\nReverse the words present in the string:\n%s",string); return 0; } void reverse(char*str) { int i,temp,size,j; size=strlen(str); j=size-1; for(i=0;i<j;i++) { temp=str[i]; str[i]=str[j]; str[j]=temp; j--; } } void rev_words(char*str) { int i, temp, temp1,j; for(i=0;str[i]!='\0';i++) { if((str[i]!=' ' && str[i-1]==' ') || i==0) temp=i; if((str[i-1]!=' ' && i>0)&&(str[i]==' ' || str[i+1]=='\0')) { if(str[i+1]=='\0') j=i; else j=i-1; for(temp;temp<j;temp++,j--) { temp1=str[temp]; str[temp]=str[j]; str[j]=temp1; } } } }
Output:
Enter the string:
Love the mother nature
Reverse the words present in the string:
nature mother the Love
Explanation:
In these program we have used two functions.
The first function "void reverse(char*) " is used to reverse the string.
The base address of the input string is passed through the call by reference in the function "void reverse(char*). A logic is used to reverse the string in the first function. As we have used call by reference the changes will be directly done in the input string.
The string will be converted as below
From this,
Love the mother nature
To This,
erutan rehtom eht evoL
The second function "void rev_words(char*)" is used to reverse the letters of each word. As we have used call by reference in these function too, the changes will be directly seen in the input string.
The string will be converted as below,
From this,
erutan rehtom eht evoL
To This,
nature mother the Love
1 Comments
There are lots of information about latest technologies and how to get trained in them,like MBA in Artificial Intelligence have spread around the web.By the way you are running a great blog. Thanks for sharing this.
ReplyDeletePost a Comment