Searching inside text in C
strchr finds a character, strstr a substring, and both return NULL when absent.
#include <string.h>
long index_of(const char *text, char target) {
const char *found = strchr(text, target);
return (found == NULL) ? -1 : (long) (found - text);
}
const char *extension_of(const char *path) {
const char *dot = strrchr(path, '.');
return (dot == NULL || dot == path) ? "" : dot + 1;
}
int contains(const char *haystack, const char *needle) {
return strstr(haystack, needle) != NULL;
}
How it works
- The return value is a pointer into the original string.
- Subtracting the base gives you the index.
strrchrsearches from the end, which suits file extensions.
Keywords and builtins used here
NULLcharconstcontainsextension_ofindex_ofintlongreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 403
- Tokens
- 120
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 72 seconds.
Step 2 of 3 in Comparing & searching, step 6 of 13 in Strings & text.