Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string starts with another string in C?

Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

"abc", "abcdef" -> true "abcdef", "abc" -> false "abd", "abdcef" -> true "abc", "abc"    -> true 
like image 523
thejh Avatar asked Jan 22 '11 22:01

thejh


People also ask

How do you check if a string contains a certain character in c?

The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found.

Is substring in c?

Implement substr() function in CThe substr() function returns the substring of a given string between two given indices. It returns the substring of the source string starting at the position m and ending at position n-1 .

How does Strncmp work in c?

In the C Programming Language, the strncmp function returns a negative, zero, or positive integer depending on whether the first n characters of the object pointed to by s1 are less than, equal to, or greater than the first n characters of the object pointed to by s2.


2 Answers

There's no standard function for this, but you can define

bool prefix(const char *pre, const char *str) {     return strncmp(pre, str, strlen(pre)) == 0; } 

We don't have to worry about str being shorter than pre because according to the C standard (7.21.4.4/2):

The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2."

like image 68
Fred Foo Avatar answered Oct 07 '22 17:10

Fred Foo


Apparently there's no standard C function for this. So:

bool startsWith(const char *pre, const char *str) {     size_t lenpre = strlen(pre),            lenstr = strlen(str);     return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0; } 

Note that the above is nice and clear, but if you're doing it in a tight loop or working with very large strings, it does not offer the best performance, as it scans the full length of both strings up front (strlen). Solutions like wj32's or Christoph's may offer better performance (although this comment about vectorization is beyond my ken of C). Also note Fred Foo's solution which avoids strlen on str (he's right, it's unnecessary if you use strncmp instead of memcmp). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.

like image 45
5 revs Avatar answered Oct 07 '22 15:10

5 revs