Saturday, May 16, 2015

indexof function in C Language program


There is no predefined indexof function in C Language. We will define a function named indexof in C language which will show the position of a character in a string.

 There will be two different indexof functions, one will take the original string as first argument and a character as the second argument. The function will show the first occurrence index location of the character in the string. If the character is not found in the string, the function will return =1.


  The second one will take the original string as first argument and a character as the second argument and an index as the third argument. The function will show the first occurrence index location of the character in the string after the specified index (3rd argument). If the character is not found in the string, the function will return =1.

  PROGRAM 1:

#include< string.h>
#include< stdio.h>
int indexof(char *,char);
 void main()
 {
  char ch[100];
  char c;
  int i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  i=indexof(ch,c);
  if(i< 0)<0 o:p="">
  printf("\nThe character %c is not present in string %s",c,ch);
  else
    printf("\nThe character %c is in index %d in string %s",c,i,ch);
  getch();
  }
int indexof(char *p,char c)
{
int i=0;
 while(*p!=NULL)
 {
 if(c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;
 }


PROGRAM 2


#include< string.h>
#include< stdio.h>
int indexof(char *,char,int);
 void main()
 {
  char ch[100];
  char c;
  int x,i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  printf("\nEnter the location after which the character to search:");
 scanf("%d",&i);
  x=indexof(ch,c,i);
 if (x< 0)
   printf("\nThe character %c is not present in string %s after index %d",c,ch,i);
  else
    printf("\nThe character %c is in index %d after index %d in string %s",c,x,i,ch);
  getch();
  }
int indexof(char *p,char c,int x)
{
int i=0;
 while(*p!=NULL)
 {
 if(i > x && c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;

 }

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner