The problem is not directly related to your use of gets()
, though (as noted in comments) you should never use gets()
because it is too dangerous.
The trouble is that:
- You don't initialize count so if the first letter of the substring is not present in the string, it is never initialized, and
- You start the inner loop with
j = 0
, which means you check the first letter twice, and count it twice, so when the search finishes with a match, you've set count
too big. A simple fix is to start the loop with j = 1
; an alternative fix would set count = 0;
before the loop.
Replacing gets()
with fgets()
plus strcspn()
and checking for EOF yields code like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char str[50], sub_str[50];
printf("Enter the main string : ");
if (fgets(str, sizeof(str), stdin) == 0)
{
fprintf(stderr, "EOF\n");
exit(EXIT_FAILURE);
}
str[strcspn(str, "\n")] = '\0';
printf("Enter the sub string : ");
if (fgets(sub_str, sizeof(sub_str), stdin) == 0)
{
fprintf(stderr, "EOF\n");
exit(EXIT_FAILURE);
}
sub_str[strcspn(sub_str, "\n")] = '\0';
printf("Haystack = [%s]\nNeedle = [%s]\n", str, sub_str);
int l_str = strlen(str);
int l_sub_str = strlen(sub_str);
int count = 0;
int i;
for (i = 0; i < l_str; i++)
{
if (str[i] == sub_str[0])
{
count = 1;
for (int j = 1; j < l_sub_str; j++)
{
if (str[i + j] == sub_str[j])
count++;
else
break;
}
}
if (count == l_sub_str)
break;
}
if (count == l_sub_str)
printf("String found at position %d (%s)\n", i + 1, &str[i]);
else
printf("No sub string\n");
return 0;
}
Sample output (program name ss11
):
$ ./ss11
Enter the main string : qwerty is
Enter the sub string : is
Haystack = [qwerty is]
Needle = [is]
String found at position 8 (is)
$ ./ss11
Enter the main string : qwerty is
Enter the sub string : z
Haystack = [qwerty is]
Needle = [z]
No sub string
$ ./ss11
Enter the main string : qwerty is
Enter the sub string : y
Haystack = [qwerty is]
Needle = [y]
String found at position 6
$ ./ss11
Enter the main string : qwerty isosceles isomer isotropic isotopes
Enter the sub string : iso
Haystack = [qwerty isosceles isomer isotropic isotopes]
Needle = [iso]
String found at position 8 (isosceles isomer isotropic isotopes)
$ ./ss11
Enter the main string : qwerty isosceles isomer isotropic isotopes
Enter the sub string : isot
Haystack = [qwerty isosceles isomer isotropic isotopes]
Needle = [isot]
String found at position 25 (isotropic isotopes)
$ ./ss11
Enter the main string : qwerty isosceles isomer isotropic isotopes
Enter the sub string : isoto
Haystack = [qwerty isosceles isomer isotropic isotopes]
Needle = [isoto]
String found at position 35 (isotopes)
$