CloudN9ne
CloudN9ne

Reputation: 235

Searching a term in a line

I have been stuck on this for ages, I just cannot think of a way to solve this problem. So, I have an array which has a list of terms, each term will be compared with an input file and then if there is a match, there will be an output which says "Match found"... One problem I have is that strncasecmp only compares the first n characters of the line. Which means I had to shift the array left every time until I reached the end.

This is what I have come up with so far...

while (fgets(line, 256, ifp) != NULL){ 
    for (i = 0; i < numberTerms; i++){
        len = strlen(term[i]);
        for (lineStep = 0; lineStep < (strlen(line) - 1); lineStep++){
            if (line[lineStep] == '\0')
                break;
            if (strncasecmp(line, term[i], len) == 0)
               printf("Match found!\n");
            for (j = 0; j < (strlen(line)-1); j++)
                line[lineStep] = line[lineStep + 1];
        }
    }
}

This only prints "Match found!" once instead of the 5 times it needs to. What am I doing wrong? Also, if there is an easier way to search strings please let me know.

Upvotes: 1

Views: 67

Answers (1)

A4L
A4L

Reputation: 17595

You could use the function strsstr to find sub-strings inside another string.

here is a sample usage:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h>

int main(int argc, char** argv)  
{ 
    char* str = "hello foo world fOo this is foo a test foo strstr";
    char* p;
    int offset = 0, len = strlen("foo");
    while((p = strstr(str+offset, "foo"))) {
        printf("Match found at offset: %d\n", (p-str));
        offset = (p-str) + len;
    }
    return 0;  
} 

The code above prints:

Match found at offset: 6
Match found at offset: 28
Match found at offset: 39

There is also a function strcasestr for case insensitiveness but it is not standard. To make your code portable you could write a function which turns both of your strings into lower case and then perform the search using strstr.

EDIT

Here is a basic function to turn a string into lower case, string returned needs to be free-ed!

#include <ctype.h>

char* strtolower(char* str)
{
    char* strlower = NULL, *p;
    if(str) {
        p = strlower = strdup(str);
        while(*p) {
            *p = tolower(*p);
            p++;
        }
    }
    return strlower;
}

Used with the above string and sub-string it should also print:

Match found at offset: 16

Upvotes: 1

Related Questions