Friday, January 30, 2009

Write a C program to displays the position or index in the string S where the string T begins, or -1 if S doesn't contain T.

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
void main( )
{
char st[10], t[10];
int i, flag=0, count=0, j, pos;
clrscr();
printf("Enter the main string:");
gets(st);
printf("Enter the sub string:");
gets(t);
for(i=0; st[i]!='\0'; i++)
{
if(st[i]==t[0])
{
pos=i;
for(j=0; t[j]!='\0'; j++)
{
if(st[i]==t[j])
count++;
i++;
}
flag=1;
break;
}
}
if(flag==1 && count==strlen(t))
printf("\nPosition: %d, And T is a substring of S", pos+1);
else if(flag==1 && count < strlen(t))
printf("\nPosition: %d, And T is not a substring of S", pos+1);
else
printf("\nIndex: -1");
getch();
}

No comments:

Post a Comment