Reputation: 721
am writing a program to find a substring in a string. For some strange reason, during comparison of one character to another, two similar characters do not match. I'm not sure if this is some sort of bug. Here's the code:
#include <stdio.h>
int first_char_compare(char *str,char a);
int main()
{
int i,j, char_exists,substring;
char string1[] = "jrsfahamfsf";
char string2[] = "ham";
char_exists = first_char_compare(string1,string2[0]);
if(!(char_exists<0))
{
j=char_exists;
for(i=0;string2[i]!='\0';i++)
{
for(;string1[j]!='\0';j++)
{
printf("%c\t%c\n",string2[i],string1[j]);
if(string1[i]==string2[j])
{
substring = 1;
printf("matches\n");
break;
}
else
{
printf("doesn't match\n");
substring = 0;
}
}
if(substring==0)
break;
j++;
}
}
if(substring)
printf("Is a substring\n");
else
printf("Not a substring\n");
return 0;
}
int first_char_compare(char *str,char a)
{
/* Checks if the first character of the substring is in the main string.
* If the character exists, it's index is returned. If it doesn't exist
* -1 is returned.
*/
int i;
for(i=0;str[i]!='\0';i++)
{
if(a==str[i])
return i;
}
return -1;
}
Upvotes: 0
Views: 103
Reputation: 36458
In your loops, string2
is indexed by i
, and string1
by j
:
for (i = 0; string2[i] != '\0'; i++)
{
for( ; string1[j] != '\0'; j++)
{
But in your comparison, the indices are backwards:
if (string1[i] == string2[j])
correct that to:
if (string1[j] == string2[i])
Upvotes: 2