Techhgeekz ™

Thursday 12 September 2013

substring in c

substring using pointers in C :-

#include <stdio.h>
#include <malloc.h>

char *substring(char*, int, int);

int main()
{
   char string[100]="c substring", *pointer;
   int position=3, length=5;

   printf("Enter a string\n%s",string);

   printf("Enter the position and length of substring\n");
   printf("%d\t%d",position,length);

   pointer = substring( string, position, length);

   printf("\nRequired substring is \"%s\"\n", pointer);

   free(pointer);

   return 0;
}

/*C substring function: It returns a pointer to the substring */

char *substring(char *string, int position, int length)
{
   char *pointer;
   int c;

  pointer = malloc(length);

   for (c = 0 ; c < position -1 ; c++)
      string++;

   for (c = 0 ; c < length ; c++)
   {
      pointer[c] = *string;      //      
*(pointer+c)=pointer[c] //both are same

      string++;  
   }

   *(pointer+c) = '\0';

   return pointer;
}

for compilation:-click here

No comments:

Post a Comment