The following C problem searches s1 inside s2 and returns the position that s1 was found in s2. i wrote this code and it works fine for values like s1: car s2: carnal but if i have s1:car and s2: cbrcarnal i think it enters an infinite loop or smth but it won’t display nothing.Can you guys see the problem? it must be in my function. Oh and I’m not allowed to use strstr.
code:
#include "stdafx.h"
#include "stdio.h"
#include "string.h"
int subsir(char s1[],char s2[],int k)
{ int n,m,i=0,j,poz=-1;
n=strlen(s1);
m=strlen(s2);
if(n>m)
return -1;
j=k;
while(j<=m-n)
if((s1[i]==s2[j])&&(s1[n-1]==s2[j+n-1]))
{
poz=j;
while(j+1<poz+n-1)
if(s1[i+1]==s2[j+1])
{i++;
j++;
}
else
return subsir(s1,s2,poz++);
}
else
j++;
if(poz!=-1)
return poz;
else
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{char s1[30],s2[30];
int n;
printf("introduceti sirul 1: ");
scanf("%s",&s1);
printf("introduceti sirul 2: ");
scanf("%s",&s2);
n=subsir(s1,s2,0);
if(n!=-1)
printf("%s is found in %s, at: %d\n",s1,s2,n);
else
printf("s %s is not found in %s\n",s1,s2);
}
Your code is sooo complicated… I honestly don’t feel like looking at it closely. But I would like to show you how I would do it