Reputation: 1148
I have two different char *
, char *string1
which is constant and char *string2
which can change. I retrieve char *string2
from a list.
I want to find the length of the shortest char *
to use it in:
strncmp(string1, string2, shortest);
.
This will be in a while-loop like below:
...
int shortest;
while (string2) {
// get the length of the shortest char *
if (!strncmp(string1, string2, shortest))
break;
string2 = list_next(list); // Returns NULL if there is no elements left
}
...
I can't use strlen(const char *s)
because it's too slow for my usecase.
Upvotes: 0
Views: 157
Reputation: 42159
For the specific case of strncmp
, you could implement the comparison function yourself to return the desired result, e.g.:
bool strprefixeq(const char *a, const char *b) {
while (*a && *b) {
if (*a++ != *b++) {
return false;
}
}
return true;
}
(Of course if you have other need for the string length, it is better to precalculate and store it, as suggested.)
Upvotes: 1
Reputation: 54363
Create a struct that contains the pointer and the length. Then you have the length precalculated and checking it should be fast.
An even better idea is to use someone else's string library that already does this for you. Besides calculating string length most of the libraries vastly improve C's buffer security by avoiding the standard string operations.
Upvotes: 2