C Program to reverse the letters in each word of the string
We will see two methods :
1. Reverse the letters in each word of the string without using function.
2. Reverse the letters in each word of the string using function.
1. Reverse the letters in each word of the string without using function.
#include <stdio.h> int main() { char string[40]; int i, temp, temp1,j; printf("Enter the string:\n"); scanf("%[^\n]%*c",string); for(i=0;string[i]!='\0';i++) { if((string[i]!=' ' && string[i-1]==' ') || i==0) temp=i; if((string[i-1]!=' ' && i>0)&&(string[i]==' ' || string[i+1]=='\0')) { if(string[i+1]=='\0') j=i; else j=i-1; for(temp;temp<j;temp++,j--) { temp1=string[temp]; string[temp]=string[j]; string[j]=temp1; } } } printf("\nReverse the letters in each word of the string:\n%s",string); return 0; }
output:
Enter the string:
Love the mother nature
Reverse the letters in each word of the string:
evoL eht rehtom erutan
2. Reverse the letters in each word of the string using function.
#include <stdio.h> void rev_letter(char*); int main() { char string[40],*c; printf("Enter the string\n:"); scanf("%[^\n]%*c",string); c=string; rev_letter(string); printf("\nReverse the letters in each word of the string:\n%s",string); return 0; } void rev_letter(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 letters in each word of the string:
evoL eht rehtom erutan
1 Comments
This comment has been removed by the author.
ReplyDeletePost a Comment