Programming Tips - C/C++: A starts_with() function for plain strings

Date: 2025apr3 Update: 2026oct3 Language: C/C++ Keywords: startsWith Q. C/C++: A starts_with() function for plain strings A. It can be done with the strstr() standard function.
bool starts_with(const char *txt, const char *target) { if (txt == nullptr && target == nullptr) return true; if (txt == nullptr || target == nullptr) return false; return strstr(txt, target) == txt; }
Full Example Use:
#include <stdio.h> #include <string.h> // (Place the above function here) int main() { { const char *txt = "one-two-three"; const char *target = "one"; printf("starts_with(%s,%s)=%s\n", txt, target, starts_with(txt,target) ? "true" : "false"); } { const char *txt = "one-two-three"; const char *target = "ONE"; printf("starts_with(%s,%s)=%s\n", txt, target, starts_with(txt,target) ? "true" : "false"); } { const char *txt = "one"; const char *target = "one-two-three"; printf("starts_with(%s,%s)=%s\n", txt, target, starts_with(txt,target) ? "true" : "false"); } }
Output:
starts_with(one-two-three,one)=true // "one-two-three" starts with "one" starts_with(one-two-three,ONE)=false // It's case sensitive starts_with(one,one-two-three)=false // Parameters are reversed