C code to find a string

strStr: c code for user defined function to find a string from multiple strings
#include<stdio.h>

int compare_string(char*, char*);

int main()
{
    char first[100], second[100], result;

    printf("Enter first string\n");
    gets(first);

    printf("Enter second string\n");
    gets(second);

    result = compare_string(first, second);

    if ( result == 0 )
       printf("Both strings are same.\n");
    else
       printf("Entered strings are not equal.\n");

    return 0;
}

int compare_string(char *first, char *second)
{
   while(*first==*second)
   {
      if ( *first == '\0' || *second == '\0' )
         break;

      first++;
      second++;
   }
   if( *first == '\0' && *second == '\0' )
      return 0;
   else
      return -1;
}

/*
OUTPUT:
-bash-3.2$ vi strStr.c
-bash-3.2$ gcc strStr.c
/tmp/ccUUzk8E.o: In function `main':
strStr.c:(.text+0x27): warning: the `gets' function is dangerous and should not be used.
-bash-3.2$ ./a.out
Enter few strings:
all is well
Enter the string to search:
code
NOT Present
-bash-3.2$ ./a.out
Enter few strings:
all is well
Enter the string to search:
all
Present at location :1
-bash-3.2$ ./a.out
Enter few strings:
all is well
Enter the string to search:
is
Present at location :5
-bash-3.2$ ./a.out
Enter few strings:
all is well
Enter the string to search:
well
Present at location :8
-bash-3.2$ ./a.out
Enter few strings:
all is well
Enter the string to search:
ll
Present at location :2
-bash-3.2$
*/
//Alternatestrstr:String search return location
#include<stdio.h>
int strStrLocation(char *str1, char *str2);
int main()
{
char str1[20];
char str2[20];
printf("Enter String1:\n");
gets(str1);
printf("Enter String2:\n");
gets(str2);
int r=0;
r=strStrLocation(str1,str2);
if(r!=-1)printf("found at %d\n",r+1);
else printf("Not found\n");
return 0;
}
int strStrLocation(char *str11, char *str22)
{
char *str1;
char *str2;
str1=str11;
str2=str22;
int location=0;
while(*str11)
{
while(*str1==*str2)
{
str1++;
str2++;
if(*str1=='\0'||*str2=='\0') break;
}
if(*str2=='\0')
break;
str11++; location++;
str1=str11;
str2=str22;
}//first while
if(*str11)
{
printf("%c\n",*str11);
return location;
}
else
return -1;
}
/*
Enter String1:
india
Enter String2:
ind
i
found at 1
-bash-3.2$ ./a.out
Enter String1:
ind
Enter String2:
india
Not found
-bash-3.2$ ./a.out
Enter String1:
india is grt
Enter String2:
grt
g
found at 10
*/

No comments:

Post a Comment