Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple Search Algorithm

Status
Not open for further replies.

fgs3124

IS-IT--Management
Mar 6, 2002
8
US

Here's an easy one for the experience programmers (of which I am not one of). I want to perform a simple search for a string value (eg. labor) in a text line I read in between the line positions of 0 to 10. I have done multiple searches out there and have come across the Boyer-Moore search algorithm (among others) but they don't seem to meet my needs.

Any one have a simple function that will do what I looking to accomplish?
 
Here is one I wrote a long time ago as a comparison between a similar function in gawk.
It's ugly and needlessly recursive, but maybe it
will give you some ideas.

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

char *Strsrch(char *,char *,int,int,int);

int main(int argc, char *argv[]) {
char *tstr;

tstr = Strsrch(argv[1],argv[2],0,0,0);

printf(&quot;%s\n&quot;, tstr);
return 0;
}


char *Strsrch(char *str, char *pat, int st, int ind, int flg) {
int x,t;
int xlen = strlen(str);
int plen = strlen(pat);
char *buf = malloc(strlen(str) * sizeof(char));

if (ind == plen) {
st = st - plen;
printf(&quot;%d index, Marker = %d, string match = %s\n&quot;, ind, st, str + st);
str = str + st;
printf(&quot;%s after truncation\n&quot;, str);
strncpy(buf,str,strlen(str));
return buf;
}

x = ind;
for (t=st ; t < xlen ; t++) {
if (str[t] == pat[ind]) {
printf(&quot;Comparing %c with %c ==match at %d\n&quot;, str[t], pat[ind],t);
t++;
x++;
return Strsrch(str,pat,t,x,1);
} else if (str[t] != pat[ind] && flg) {
printf(&quot;Failed to continue match at %d , %c\n&quot;, ind, pat[ind]);
t++;
return Strsrch(str,pat,t,0,0);
}
}
strcpy(buf,&quot;NOMATCH&quot;);
return buf;
}
 
Thanks! Got the code to compile in MSVC++ v6. It appears you are passing the program some arguments . . . is that right? If so, can you give an example?
 
Called right now like:
program name &quot;string to find match in&quot; &quot;match&quot;

But the function is the important part. You should be
able to freestyle off of the idea to get what you need.

For instance if I have an array char *:
char *match;
for (i=0 ; i < alen ; i++) {
match = Strsrch(array,array[i+1],0,0,0);
}

or a file:
FILE *myf;
char buf[256];
int y;
while ( (y = fgets(buf,256,myf)) != NULL) {
Strsearch(&quot;Testpattern&quot;,buf,0,0,0);
}
etc..

HTH.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top