In my book there is a exercise for me to try and do a search which is both case sensitive and insensitive
I did it however Im interested in knowing if there is an easier way or more efficient way
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *caseSensitive(char *string, char *match);
char *caseInSensitive(char *string, char *match);
int main(void)
{
char string[100], match[100], *ptr, *pos;
int searchtype;
printf("Enter a string to be searched: ");
fgets(string, sizeof string, stdin);
if ((ptr=strchr(string,'\n'))!=NULL)
*ptr = '\0';
printf("String to match: ");
fgets(match, sizeof match, stdin);
if ((ptr=strchr(match,'\n'))!=NULL)
*ptr = '\0';
printf("\n1 for case sensitive search\n2 for case insensitive search\n");
scanf("%d",&searchtype);
if (searchtype == 1)
{
pos = caseSensitive(string, match);
if (pos==NULL)
printf("%s wasnt found in %s\n",match,string);
else
printf("%s was found in %s at position %d\n",match, string,(pos-string));
}
else
{
pos = caseInSensitive(string, match);
if (pos==NULL)
printf("%s wasnt found in %s\n",match,string);
else
printf("%s was found in %s at position %d\n",match, string,(pos-string));
}
return 0;
}
char *caseSensitive(char *string, char *match)
{
char *pos;
pos = strstr(string,match);
return pos;
}
char *caseInSensitive(char *string, char *match)
{
char *pos;
int i;
for (i=0;i<strlen(string);i++)
(string)[i]=tolower((string)[i]);
for (i=0;i<strlen(match);i++)
(match)[i]=tolower((match)[i]);
pos = strstr(string,match);
return pos;
}