While you have a good presentation of your question, it is still a bit unclear exactly what you are looking to extract between $GPTXT
and '$'
given that you have the "\r\n"
prior to the terminating '$'
. It seems unlikely that you would want to retain the carriage return/line feed as part of your returned substring. My best interpretation is that you want "->SOME CODES HERE<-"
extracted from the string (drop a comment if this is incorrect).
If this is the case, you can use the \r\n
to your advantage in tokenizing the string to return that part between $GPTXT
and "\r\n$"
by using "\r\n$"
as the delimiters passed to strtok
. The only additional task needed in your findstr
function would be to step past your search string before calling strtok
.
In looking at the declaration for findstring
, I would tweak the parameters just a bit to make them consistent with most of the other string library functions. That being to reverse the source and dest parameters such that dest
comes before src
as in strcpy, etc...
I'm not a fan of one way over the other, but I have found keeping functions at least as consistent as possible helps avoid inadvertent parameter swaps.
I would also change your termChar
to a const char*
parameter to allow flexibility in passing the delimiter to use with strtok
.
An implementation might look like:
#include <stdio.h>#include <string.h>#define TERM 32#define MAXC 1024#define DELIM "\r\n$"char *findstr (char *dest, const char *src, size_t len, const char *srch, const char *delim){ char *p = strstr (src, srch); /* locate beginning of search in src */ size_t toklen = 0; /* token length to calculate once */ if (!p) /* validate or return NULL */ return NULL; p += strlen (srch); /* step past search str */ /* tokenize p based on delim and validate length < len */ if ((p = strtok (p, delim)) && (toklen = strlen(p)) < len) memcpy (dest, p, toklen+1); /* copy to dest w/nul-char */ else return NULL; /* or return NULL */ return dest;}int main (void) { char buffer[] = "blablabla$GPTXT->SOME CODES HERE<-\r\n$GPRMCblablabla"; char sub[MAXC] = ""; if (findstr (sub, buffer, MAXC, "GPTXT", DELIM)) printf ("sub: '%s'\n", sub);}
(note: since you have already scanned to length of your token to validate it is less than len
, there is no need to scan again by using strcpy
to effect the token copy to dest
, simply using memcpy
will provide an ever-so-slightly more efficient copy)
Example Use/Output
While provides:
$ ./bin/findstrsub: '->SOME CODES HERE<-'
If you are looking to parse something slightly different, let me know.