Hi, the following is the code for returning the position of a substring within a string(Brute force algorithm)

//Brute Force Algorithm

#include<stdio.h>
#include<string.h>

int main(void)
{
 char s1[20],s2[10];
 int x1,x2,j,k,i;
 printf("Enter string 1:");
 gets(s1);
 printf("Enter string 2:");
 gets(s2);

 x1=strlen(s1);
 x2=strlen(s2);

 if(x1<x2)
 return 0;

 for(i=0;i<=x1-x2;i++)
 {
  j=i;                     
  k=0;
  while((s1[j]==s2[k])&&k<x2)
  {
	j++;
	k++;
  }
  if(k==x2)
  printf("%d",i);
  break;
 }
return 0;
}

When I run the program, it does not print the position of the substring. What is the error? Help!!

Because you need to add { and } around lines 30-32. The break statement is not within the if statement, so the loop on line 21 exits on the first iteration of that loop.

Oh, that was a silly mistake, I spend a lot of time but could not find it, thanks a lot!!

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main(void)
{
 char s1[20],s2[10];
 int x1,x2,j,k,i;
 printf("Enter string 1:");
 gets(s1);
 printf("Enter string 2:");
 gets(s2);

 x1=strlen(s1);
 x2=strlen(s2);
 for(i=0;i<=x1-x2;i++)
 {
  j=i;                     
  k=0;
  while((s1[j]==s2[k])&& (k<x2))
  {
	j++;
	k++;
  }
  if(k==x2)
  printf("You were found....");
 }
getch();
}

as goog as...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.