Friday, May 15, 2015

substring function in C Language program


There is no predefined substring function in C Language. We will define a function named substring in C language which will extract a part of the string from the original string.

 There will be two different substring functions, one will take the original string as first argument and an index of the string as the second argument. A part of the string from the location specified by the index value of the string upto the end of the string will be extracted.

  The second substring function will take the original string as first argument, an index of the string as the second argument and number of characters as the third argument. The function will extract a substring from the original string of specified characters (3rd argument) starting from the starting index (2nd argument).


  PROGRAM 1:

#include< string.h>
#include< stdio.h>
char * substring(char *,int);
 void main()
 {
  char ch[100];
  int i;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
 ptr=substring(ch,i);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i)
 str[x++]=*p;
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }

 PROGRAM 2


#include< string.h>
#include< stdio.h>
char * substring(char *,int,int);
 void main()
 {
  char ch[100];
  int i,j;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
  printf("\nEnter the number of characters to extract:");
  scanf("%d",&j);

 ptr=substring(ch,i,j);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i,int j)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i && c str[x++]=*p)
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner