Today I just found out this problem to reverse words in a string, and thought to
code it in C. Feel free to comment :)
//Program to reverse words in a string ex: o/p: elbA saw I ere I was Able
//for i/p: Able was I ere I saw elbA
// Author: SantoshPaluri
#include<stdio.h>
#include<string.h>
char *strnrev(char *,int,int);
int main()
{
//a^=b^=a^=b; code to swap two variables without using a temporary variable
// char a[100];
char a[]="Able was I ere I saw elbA";
int i=0,j=0,send_start=0,send_end=strlen(a)-1;
// gets(a);// To get input from user, remember to define size of a
send_start=0,send_end=strlen(a)-1;
printf("The given string is: \n");
puts(a);
strnrev(a,send_start,send_end);
printf("The reverse of the whole string is: \n");
puts(a);
for(i=0;a[i]!='\0';i++)
if(a[i]==' ')
{
send_end=i-1;
strnrev(a,send_start,send_end);
send_start=i+1;
}
else if(i==strlen(a)-1)
strnrev(a,send_start,i);
printf(" The final string with also the words reversed is: \n");
puts(a);
}
char *strnrev(char *c,int recv_s,int recv_e)
{
int i=0,j,temp=0;
for(i=recv_s,j=recv_e;recv_s<recv_e;recv_s++,recv_e--)
{
temp=c[recv_s];
c[recv_s]=c[recv_e];
c[recv_e]=temp;
}
return c;
}
Sunday, July 15, 2007
Subscribe to:
Posts (Atom)