Friday 25 August 2017

FIND INDEX OF SUBSTRING IN A STRING

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function 
search(char pat[], char txt[]) that prints all occurrences of pat[] 
in txt[]. You may assume that n > m.
E.g.:
1) 
Input:
txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"

Output:
Pattern found at index 10

2)
Input:
txt[] = "AABAACAADAABAAABAA"
pat[] = "AABA"

Output:
Pattern found at index 0

#include<stdio.h>
#include<string.h>
void main()
{
    char original[30];
    char ori[30];
    int  count=0,count1=0,i,j;
    scanf("%[^\n]s",original);
    scanf("%s",ori);
    for(i=0;i<strlen(original);)
    {
        j=0;
        count=0;
        while(original[i]==ori[j])
        {
            count++;
            i++;
            j++;
        }
        int l2=strlen(ori);
        if(count==l2)
        {
            printf("Position %d",i-l2);
             break;
        }
        else
            i++;           
    }       
}

 OR

2)

 #include <stdio.h>
#include<string.h>
int main(void)
{
    char str1[100],str2[100],*ret;
    scanf("%[^\n]s",str1);
    scanf("%s",str2);
    ret=strstr(str1,str2);
    if(ret)
        printf("%d",ret-str1);
    else
        printf("Not found");
    return 0;
}

No comments:

Post a Comment