Hi all
The string_in function below is intended to take two string pointers as arguments and if the first is contained in the second, return the address at which the contained string begins.
#include <stdio.h>
#include <string.h>
#define TEST "This ain't a drill"
char * string_in (char * str1, char * str2) ;
int main (void)
{
char instr [10] ;
char * res ;
printf ("Please enter the string to look for:"
"(EOF to quit)\n") ;
while ((gets(instr)) != NULL)
{
if ((res = string_in (instr, TEST)) != NULL)
printf ("%s is located %d characters into TEST.\n",
instr, res - TEST) ;
else
printf ("Nope.\n") ;
}
printf ("Thanks for playing...\n") ;
}
char * string_in (char * str1, char * str2)
{
int i, j ;
char * res ;
for (i = 0; i < strlen (str2); i++)
{
if (str2[i] == str1[0])
{
res = str2 + i ;
for (j = 0; j < strlen (str1); j++)
{
if (str2[i + j] != str1[j])
{
res = NULL ;
break ;
}
}
}
}
return res ;
}
I get the following output when testing it:
geoff@geoff-laptop:~/prog/C$ gcc string_in.c -o string_in
/tmp/ccATd9U0.o: In function `main':
string_in.c:(.text+0x80): warning: the `gets' function is dangerous and should not be used.
geoff@geoff-laptop:~/prog/C$ ./string_in
Please enter the string to look for:(EOF to quit)
This
This is located 0 characters into TEST.
ain't
Nope.
ain
Nope.
ai
Nope.
a
a is located 11 characters into TEST.
Thanks for playing...
I figure that the reason why "ain't" is not picked up here must have something to do with the apostrophe, but for the life of me I can't see what :confused: I also tested "This ain't" and got a positive result. Could it have something to do with using gets()?