Sample programs to tackle some common interview questions.

A sentence reverse application.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *in_str = "This is a string to be reversed";

int cpy_char(char* dst,char *src,int size)
{
  int i= 0;
  for (i = 0; i<size; i++)
    {
      dst[i] =(char) src[i];
    }
  return i;
}

char *reverse_sen(char *in_str)
{
  int size=strlen(in_str);
  char *padDest = alloca(size+2);
  char *startP;
  char *endP;
  char *destP = malloc(size+1);
  char *destI = destP;
  int wordSize = 0;

/* memsets */
  memset(destP,0,size + 1);
  memset(padDest,0,size+2);

/* create a padded version space at front */
  strcat(padDest," ");
  strcat(padDest,in_str);
  startP = padDest;
  endP = padDest + size + 1;
  /* step back from the Null terminator */
  endP--;


while(endP >= startP)
{
    if(*endP == 0x20)
      {
	endP--;
	if(wordSize > 0)
	  {/*Store a word */
	   cpy_char(destP,&endP[2],wordSize);
	   destP += wordSize;
	   *destP=0x20;
	   destP++;
	   wordSize = 0;
	  }
      }
    else if(*endP != 0x20)
      { /* load a word */
	   wordSize = 0;
	   while (*endP != 0x20)
	         {
	           wordSize++;
	          endP--;
		 }
       }
}
return(destI);
}


int main()
{
  char *ret = reverse_sen(in_str);
  printf("In String= %s\n",in_str);
  printf("reversed sentence = %s\n",ret);
  if(ret)
  free(ret);

  return (0);
}