-
strstr problem...
Hi folks...
So this is my Code:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Find a Word in this String", *str2 = "Word", *ptr;
ptr = strstr(str1, str2);
if(ptr)
printf("String Found");
else
printf("Not Found !");
}
:confused:
but this code did not fulfill my expectations...
So to my problem...
1. How can I search for a word in a string non-Case senstive... (using this code)
2. strstr also gives a ptr = 1 if I search for 'ord', is there any possibility to search for the exact phrase... 'word' only conisdering the non-Casetive function (again using this code)
Thanks in advance
Client :cool:
-
>1. How can I search for a word in a string non-Case senstive... (using this code)
Well instead of using strstr you will have to use a function that does not depend on case. I have one here available from the merlin functions. It is called mstrstr and can be used just like strstr.
Code:
char* mstrstr(char *s1, const char *s2)
{
size_t i, value;
char *p;
char *s1b, *s2b;
if (strlen(s1)<strlen(s2))
return NULL;
if (*s1=='\0' || *s2=='\0')
return NULL;
s1b=malloc(strlen(s1)+1);
s2b=malloc(strlen(s2)+1);
if(s1b==NULL || s2b==NULL)
{
free(s1b);
free(s2b);
return NULL;
}
strcpy(s1b, s1);
strcpy(s2b, s2);
for(i=0; (s1b[i]=tolower(s1b[i]))!=0; i++)
;
for(i=0; (s2b[i]=tolower(s2b[i]))!=0; ++i)
;
p=strstr(s1b, s2b);
if(p==0)
{
free(s1b);
free(s2b);
return NULL;
}
else
{
value=p-s1b;
free(s1b);
free(s2b);
return &s1[value];
}
}
- Sean
-
Re: strstr problem...
>1. How can I search for a word in a string non-Case senstive... (using this code)
You can't using that code. I'd suggest you convert both strings to lower case, then do the same search again.
>2. strstr also gives a ptr = 1 if I search for 'ord', is there any possibility to search for the exact phrase... 'word' only conisdering the non-Casetive function (again using this code)
First ptr will not be 1, it will be a memory address, it's the pointer to the start of the second string, as found within the first. If you are looking for a complete word, why not surround you searchfor word with spaces. Special care would need to be taken if the word had a comma after it, or if it was at the end of the string, but it'd be a start.
Another way I can think of is to do a search without searchfor being surrounded by spaces, and when you find it, check the character before and after to see if they are valid word breakers (space, comma, period etc).