tags:

views:

215

answers:

5
int mystery( const char *s1, const char *s2 ) {
  for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {
    if( *s1 != *s2 ) {
      return 0;
    } //end if
  } //end for
  return 1;
}

I know it has typing errors but this is exactly how it was.

+12  A: 

It compares two strings, returning 1 if string one starts with string two, or vice-versa and 0 if not.

klausbyskov
ahhh you beat me :) ill remove my answer. +1 for speediness
Mark Synowiec
Compares two strings for equality.
A_Nablsi
That's not correct. "Foo" and "FooBar" will evaluate as 1.
sharth
@sharth, well spotted. I have updated my answer.
klausbyskov
Deleted comment, answer was updated
Colin
It also returns 1 if one of the strings is empty, that is it contains just '\0'
JBrooks
@JBrooks, correct. With a loose enough definition of *starts with* I think the answer covers that fact.
klausbyskov
A: 

Looks like this function returns 1 when the two strings are equal and 0 when they are not.

At least, this may have been the intention.

Gunner
+4  A: 

It returns 0 if the shorter of (s1, s2) is not the same as the beginning of the longer one. The strings can be different lengths, but one must be a substring starting at the beginning of the other.

Edit. Oops sharth beat me to it. Vote him up before me.

sskuce
+2  A: 

Is it worth explaining?

 for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) {

The first element in a for loop, before the first ';' does the initial setup, here none is required.
So the for loop runs while either of the characters pointed at by s1 and s2 are not zero. Zero marks the end of string in c and c++.
The last part of the for loop is what extra to do on each loop - in this case moves the pointers s1 and s2 to point to the next character in each of the strings.

   if( *s1 != *s2 ) {
      return 0;

If the characters pointed at by s1 and s2 aren't the same - ie we have found the first different character in the two strings, return 0 ie false

return 1;

If we get to the end of one of the strings and we haven't found any characters that were different return 1 - ie true.

So the function returns true if the strings are identical or one string begins with the other, and false is the strings have and different characters.

Martin Beckett
@Martin: Why "is it worth explaining?"?
Chris
The last line isn't necessarily true. While "Foo" is a substring of "BarFooBar", it will still return false.
sharth
@sharth - thanks, should have said initial sub-string. Tried to put it in less technical terms
Martin Beckett
+1  A: 
Zango
Or perhaps, return s1.startsWith(s2) || s2.startsWith(s1);
sharth