C strstr
Look for a literal sequence anywhere in a label before displaying matching stock.
A simple example
strstr
- Start with "abc", looking for "b"
- Do this Search inside the text
- Result Found
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "abc";
const char *other = "b";
printf("%s\n", (strstr(value, other) != NULL) ? "yes" : "no");
return 0;
}
yes
Syntax
strstr(label, "tea") != NULL
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonFind a word on a shelf label
A stockroom worker searches a shelf description for a particular word. Inspect the match result before using it to highlight the relevant part of the shelf label.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *label = "green tea bags";
printf("%s\n", (strstr(label, "tea") != NULL) ? "yes" : "no");
return 0;
}
yes
The letters t-e-a occur consecutively in the label. The check would also match teapot.
Find an ingredient in a lunch order
A search box accepts a short piece of text and looks for it inside a longer description. Check where the sequence occurs before deciding whether the product or shelf label belongs in the results.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "iced tea";
const char *other = "tea";
printf("%s\n", (strstr(value, other) != NULL) ? "yes" : "no");
return 0;
}
yes
The letters of tea occur together at the end.
Check a filename for a literal dot
A filename filter looks for an actual period between a name and its extension. Treat the period as a literal character so an unrelated filename cannot match merely because it contains some character.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "readme";
const char *other = ".";
printf("%s\n", (strstr(value, other) != NULL) ? "yes" : "no");
return 0;
}
no
A dot has no special meaning during a literal search.
Route a lift fault to the right team
A caretaker receives a ticket with the text “East lift stalled on floor 2”. Tickets mentioning a lift go to the lift crew. The incoming system uses lower-case equipment names consistently.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *ticket = "East lift stalled on floor 2";
puts(strstr(ticket, "lift") ? "Lift crew" : "General repairs");
return 0;
}
Lift crew
The word lift occurs inside the ticket text, so the ticket is routed to the lift crew. A search for a literal substring also matches inside longer words.
What to watch for
For whole-word searching, specify word boundaries rather than a plain substring.