Sunday 4 July 2010

Check if a string is a subsequence of another string

#include <stdio.h>
#include <string.h>
#include <conio.h>
int check_subsequence (char [], char[]);

void main ()
{
 int flag;
 char s1[1000], s2[1000];
 clrscr();
 printf("Input first string\n");
 gets(s1);
 printf("Input second string\n");
 gets(s2);
/** Passing smaller length string first */
if (strlen(s1) < strlen(s2))
 flag = check_subsequence(s1, s2);
 else
 flag = check_subsequence(s2, s1);
(flag)?printf("YES\n"):printf("NO\n");
getch();
}
int check_subsequence (char a[], char b[]) {
 int c, d;

 c = d = 0;

 while (a[c] != '\0') {
 while ((a[c] != b[d]) && b[d] != '\0') {
 d++;
 }
 if (b[d] == '\0')
 break;
 d++;
 c++;
 }
 if (a[c] == '\0')
 return 1;
 else
 return 0;
}

You may like the following posts:
Arrays
Strings
Data type

No comments:

Post a Comment