Steven said:
I have a question about strcmp(). I have four words, who need to be
compared if it were two strings. I tried adding the comparison values
like '(strcmp(w1, w2) + strcmp(w3, w4))', where w1 and w2 make up the
first string and, w3 and w4 make up the second string. I do not want
to allocate memory, then put the words together to create a string
only to facilitate strcmp() comparison.
My question; Does anyone know how to get the same strcmp() return
value I would normally get when comparing the four words like if they
were two strings ?
You need to define the problem more precisely. You say you have "four
words"; I presume you have a pointer to each word, which is stored as
a string (w1, w2, w3, w4), so strcmp(w1, w2) would compare the first
and second words. So far, that's clear enough.
You then say you need to compare the four words "as if it were two
strings". Well, they're not two strings, they're four strings. There
are a multitude of ways you could treat them "as if" they were two
strings.
The first thing you should do is define precisely, in English, just
what you're looking for. Once you've done that, you can nail down
your definition by writing something in C that's functionally what you
want, but not necessarily as efficient as you want it.
Here's an example of what you *might* mean:
int compare(char *w1, char *w2, char *w3, char *w4)
{
char *s1 = malloc(strlen(w1) + strlen(w2) + 1);
char *s2 = malloc(strlen(w3) + strlen(w4) + 1);
int result;
if (s1 == NULL || s2 == NULL) {
/* Insert error handling here. */
}
strcpy(s1, w1);
strcat(s1, w2);
strcpy(s2, w3);
strcat(s2, w4);
result = strcmp(s1, s2);
free(s1);
free(s2);
return result;
}
If C supported "+" as a string concatenation operator, this would be
equivalent to strcmp(w1+w2, w3+w4). That may or may not be what you
want. Since you refer to the input strings as "words", it might also
make sense to concatenate them together with a space between them.
Finally, *why* don't you want to "allocate then put the words together
to create a string only to facilitate strcmp() comparison"? If I
understand your problem statement correctly, that seems like the most
obvious way to approach the problem. If you're worried about
efficiency, and you'd rather compare the strings in place, that's
reasonable, but you should consider getting something working first,
then worry later about making it more efficient. You might find that
the allocation isn't a bottleneck, and optimizing that code might not
be worth the effort. On the other hand, if that is a bottleneck,
there are probably ways to write a strcmp() replacement that traverses
pairs of strings rather than single strings.
Describe more precisely what you're trying to do, and perhaps we can
help you do it.