strstr whole string match
I'm trying to match the whole string and not just part of it. For instance, if the needle
is 2
, I would like to match just the string 2
and not 20, 02, or 22
or anything related.
I'm using strstr
as:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file;
char l[BUFSIZ];
int linenumber = 1;
char term[6] = "2";
file = fopen(argv[1], "r");
if(file != NULL) {
while(fgets(l, sizeof(l), file)){
if(strstr(l, term) != NULL) {
printf("Search Term Found at %d!\n", linenumber);
开发者_运维知识库 }
++linenumber;
}
}
else {
perror(argv[1]);
}
fclose(file);
return 0;
}
Use strcmp
instead of strstr
or, for a better answer, define "anything related".
strstr
is matching the string "2"
. If you don't want it to match things where 2
is combined with other things, you're going have to define exactly what "just the string 2
" means. Is it 2
surrounded by whitespace?
I'm guessing what you really want to do is to tokenize the input (perhaps delimited on whitespace or something) and then check whether a token is the string "2"
. (In that case, use strtok
and strcmp
.)
You have to define what a complete string is. In your example "02" "22" and "20" are rightly matched as "2" is completely matching in them. If you want to only match "words" you have to define what are the characters part of "words" and what characters are delimiters. Often whitespaces are sufficient (check with isblank
or isspace
as tabs an non breaking spaces (\xA0 in ANSI coding) are checked). Sometimes you may have other separator characters ".,;/:+-()!?" etc. . In that case you have to use strtok
or if you can't (or don't want) to modify the input string, you can use strspn
and strcspn
. Or even better, in that case, use a regular expression library.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file;
char l[BUFSIZ];
int linenumber = 1;
char term[6] = "2";
char *p=NULL;
file = fopen(argv[1], "r");
if(file != NULL) {
while(fgets(l, sizeof(l), file)){
p=l;
while((p=strtok(p, " \r\n\0")) != NULL) { // split token with any delimiter \r or \n or \0 or space
if(strcmp(p,term) == 0) //then check each word with term
printf("Search Term Found at %d!\n", linenumber );
p = NULL; //must be null to fetch next word in the line
}
++linenumber;
}
}
else {
perror(argv[1]);
}
fclose(file);
return 0;
}
Use Leading and trailing spaces
To find "2" as a unique word and not part of other words:
- Try strstr-ing for " 2 " (note the leading and trailing space chars).
NOTE: As a special case,
Search the first two chars for "2 " and
Search the last two chars for " 2" in your file.
精彩评论