Thursday, February 16, 2012

C Interview Question: Program to reverse words from the string

Program to reverse a words from the string:
below program will
input:This is me 123456789
output: sihT si em 987654321

#include
#include
#include


void reverseWord (char *word, int size)
{
char tempc;
if( size <= 1)
return ;
tempc= *word;
*word=*(word+size-1);
*(word+size-1)=tempc;
reverseWord(word+1,size-2);


}
int main()
{

char inputStr[]={"This is me 123456789"};
char* strPtr=inputStr;
char* wordHeadPtr=strPtr;
int count=0;
printf("Input string is : %s \n",inputStr);

do
{

if((*strPtr=='\0') || (*strPtr==32))
{
reverseWord(wordHeadPtr,count);
if(*strPtr== '\0')
break;
count=0;
strPtr++;
wordHeadPtr=strPtr;
}
else{

count++;
strPtr++;
}
}
while(strPtr);

printf("Final string is : %s \n",inputStr);
}

No comments:

Post a Comment