# Thread: first occurence in s1 compared to s2

1. ## first occurence in s1 compared to s2

the following to pieces of code are functions i have attempted to write. its suppose to return the first location in s1 that any character in s2 occurs.

my question is why doesnt the first set of code work? i think its because of the 2nd for loop that has s2[j] != s1[i] but im not sure. the only differences between the first and a second sets of code is the extra variable and the "s2[j] !=s1[i]" part.

for those of you that have k&r this is ex. 2-5.
thanks in advance for response guys...and girls.

Code:
```//non-working code

int any(char s1[], char s2[])
{
int i,j;

for(i = 0; s1[i] != '\0'; i++)
{
for(j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++)
{
if (s1[i] == s2[j])
return i;
else
return -1;
}
}
}```
Code:
```int any(char s1[], char s2[])
{
//working code
int   i;
int   j;
int   pos;

pos = -1;
for (i = 0; s1[i] != '\0' && pos == -1; i++)
{
for (j = 0; s2[j] != '\0' && pos == -1; j++)
{
if (s2[j] == s1[i])
{
pos = i;
return pos;
}
}
}
}```
i

2. Code:
```int any(char s1[], char s2[])
{
int i,j;

for(i = 0; s1[i] != '\0'; i++)
{
for(j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++)
{
if (s1[i] == s2[j])
return i;
else
return -1;
}
}
}```
move return -1 outside both loops
This because you want to go thrue every character
in s1. Now your program only looks at the first character.
If s1[0] == s2[0] return 0 else return -1

3. Actually you're both wrong. If you are trying to get it to return the indices on any matching character, then you do not return when it isn't a match. Otherwise all that happens is it checks one single character. If that character matches, it returns 0, because that's the first indices, otherwise it returns -1.

You want to do nothing on a non-match, so that it continues through the loop.

If at the end you are outside of the loop, then you know that thee was no match, so then return -1.

Quzah.

4. Code:
```int any(char s1[], char s2[])
{
int i,j;

for(i = 0; s1[i] != '\0'; i++)
{
for(j = 0; s2[j] != '\0' && s2[j] != s1[i]; j++)
;

if (s1[i] == s2[j])
return i;
}

return -1;
}```

5. Actually you're both wrong. If you are trying to get it to return the indices on any matching character, then you do not return when it isn't a match. Otherwise all that happens is it checks one single character. If that character matches, it returns 0, because that's the first indices, otherwise it returns -1.
Wasnt i actually saying this or is my english bad?

6. Originally posted by C-learning
Wasnt i actually saying this or is my english bad?
Yeah. You did. I just looked at the code you posted and assumed you were posting your version rather than quoting theirs. I just looked at the code rather than what you wrote. :P

Quzah.