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
Use
strstr()
function.Stra == strstr(stra, strb)
Because I ran the accepted version and had a problem with a very long str, I had to add in the following logic:
Or a combination of the two approaches:
An additional idea is to compare block-wise. If the block is not equal compare that block with the original function:
The constants
13
,64
,4096
, as well as the exponentiation of theblock_size
are just guesses. It would have to be selected for the used input data and hardware.Apparently there's no standard C function for this. So:
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 may 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 avoidsstrlen
onstr
(he's right, it's unnecessary). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.I'm no expert at writing elegant code, but...
There's no standard function for this, but you can define
We don't have to worry about
str
being shorter thanpre
because according to the C standard (7.21.4.4/2):