Thursday, March 8, 2012

Find substring

Write a C program that takes two strings (string a, string b) and gives the first occurrence of string b in string a.

#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
int comparelen(char *st1, char* st2);
void main()
{
    int len1,len2;
    char str1[]="ABCDEFGHIJ";
    char str2[]="HIJK";
    char* ptr=str1;
    int t=1,pos=0;
    printf("\n strings are %s %s",str1,str2);
    getchar();
    len1=strlen(str1);
    len2=strlen(str2);
        printf("\n strings are %d %d",len1,len2);
        getchar();               
        getchar();
        while(pos<=(len1-len2) && (t!=0))
        {
            t=comparelen(ptr,str2);
            printf("\n pos and t %d %d",pos,t);
            if(t==-1)
            {
                ptr++;
                pos=pos+1;
            }
            else if(t==0)
            {
                printf("\n found at pos %d",pos);
                getchar();
            }
        }
        if(t==-1)
        {
            printf("\n not found at all");
            getchar();
        }
}

int comparelen(char *st1, char* st2)
{
    for(int i=0;i<strlen(st2);i++)
    {
        if(st1[i]==st2[i])
        {
            st1++; st2++;
        }
        else
            return -1;
    }
    return 0;
}

No comments:

Post a Comment