Pawan Sharma
BAN USER#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// this program reverse string as follows : hello string --> olleh gnirts
void reverse(char[], int, int);
int main()
{
int l;
printf("enter the length of string\n");
scanf("%d", &l) ;
getchar();
char *str = malloc(sizeof(char) * l);
printf("enter the string\n");
gets( str);
int first = 0,i,last;
int len = strlen(str);
for(i=0; i<len; i++)
{
if(str[i] == ' ')
{
last = i-1;
reverse(str,first,last);
first = i+1;
}
if(i == len-1)
{
last = len-1;
reverse(str,first,last);
}
}
printf("%s\n", str);
}
void reverse(char str[], int first, int last)
{
int i,j;
char temp;
for(i=first,j=last; i<j; i++,j--)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
// its complexity is O(n*n) ..can anybody suggest some better algorithm?
- Pawan Sharma May 23, 2012