Re: Question on strncmp / strnicmp use
- From: vippstar@xxxxxxxxx
- Date: Fri, 16 Jan 2009 08:13:59 -0800 (PST)
On Jan 16, 5:52 pm, Ben Bacarisse <ben.use...@xxxxxxxxx> wrote:
vipps...@xxxxxxxxx writes:
On Jan 16, 5:05 pm, C. J. Clegg <answer.in.newsgr...@xxxxxxxxx> wrote:
I have two null-terminated character strings, str1 and str2. I don't
know which one is longer, but I want to know if the shortest one
(whichever one that might be) matches the first part of the longer
one.
I can say:
if ( strncmp( str1, str2, strlen( str2 ) ) == 0 ||
strncmp( str2, str1, strlen( str1 ) ) == 0 )
but that seems a bit kludgy and inelegant.
Is there a better way?
Writing your own function is the most efficient way, and also a good
solution.
It's more efficient than strncmp, because for strncmp you have to pass
the length too, which you usually compute with strlen, which means you
iterate the string one more time than needed.
Very similar tests are need when one writes this function. You have
to test the characters from both strings and increment two pointers.
strlen might well be kinder on the cache and might use a single
machine instruction. Anyway, my point is that I, for one, am
constantly amazed by how often my intuition about efficiency wrong.
This means that you could well be right, of course!
Here's what I have in mind:
strlen can't be less than O(n) (optimizations that, say, check 4
elements at once are still O(n))
mycomparison can't be less than O(n).
Using just mycomparison instead of strlen + mycomparison is one less O
(n) function called, so in that way, I'm correct.
You mention increment of pointers and comparison, but those operations
are O(1).
All that is not supported by the standard which doesn't even mention
the concept of efficiency/time of operation, but I hope you can see
what I'm trying to say.
int mycomparison(const char *s1, const char *s2) {
for(; *s1 == *s2; s1++, s2++);
This loop has UB. If the strings are the same length it starts to
look beyond the nulls. Of course, this may be well-defined but, in
general, it is not safe.
Yes, you are right. Fix: (I hope)
for(; *s1 == *s2; s1++, s2++) if(*s1 == 0) break;
.
- Follow-Ups:
- Re: Question on strncmp / strnicmp use
- From: Barry Schwarz
- Re: Question on strncmp / strnicmp use
- From: Ben Bacarisse
- Re: Question on strncmp / strnicmp use
- References:
- Question on strncmp / strnicmp use
- From: C . J . Clegg
- Re: Question on strncmp / strnicmp use
- From: vippstar
- Re: Question on strncmp / strnicmp use
- From: Ben Bacarisse
- Question on strncmp / strnicmp use
- Prev by Date: Re: Question on strncmp / strnicmp use
- Next by Date: Re: Question on strncmp / strnicmp use
- Previous by thread: Re: Question on strncmp / strnicmp use
- Next by thread: Re: Question on strncmp / strnicmp use
- Index(es):
Relevant Pages
|