The function f
is doing some character-by-character comparison of 2 strings. It's not a strcmp
, because the indexes i
and j
are not advancing simultaneously (i.e. it's not just comparing s[0]
with t[0]
, s[1]
with t[1]
, etc.)
Look closely at the nested loops. The j
loop goes over all the positions in the second string for every value of i
, which loops over the positions in the first string.
As soon as any matching character is found, the function returns.
So if s[0]
matches any character in t
, 0
will be returned.
If s[0]
doesn't matching any character in t
, but s[1]
does match some character in t
, 1
will be returned.
And so on. What gets returned is the index of the first character in s
that matches any character in t
.
If the 2 strings have no characters in common, the -1
at the end is returned.
Except for the -1
case and the return type, this function is the same as strcspn
.
Since the array index operator is a form of pointer arithmetic, there is plenty of pointer arithmetic in the code already.
Overlooking that objection for the sake of exam points, one possible method of rewriting it proceeds like this:
/* Step 1: replace foo[bar] with *(foo+bar) */
int f1 (char s[], char t[]) {
int i, j;
for (i=0; *(s+i) !='\0'; i++)
for (j=0; *(t+j) !='\0'; j++)
if (*(s+i)==*(t+j)) return i;
return -1;
}
/* Step 2: introduce new loop variables p and q. Every time the original
code modifies i and j, you modify p and q so that p==s+i and q==t+j. */
int f2 (char s[], char t[]) {
int i, j;
char *p, *q;
for (i=0,p=s; *(s+i) !='\0'; i++,p++)
for (j=0,q=t; *(t+j) !='\0'; j++,q++)
if (*(s+i)==*(t+j)) return i;
return -1;
}
/* Step 3: Replace s+i with p and t+j with q. Replace i with p-s. These
are correct because of the work you did in step 2. */
int f3 (char s[], char t[]) {
int i, j;
char *p, *q;
for (i=0,p=s; *p !='\0'; i++,p++)
for (j=0,q=t; *q !='\0'; j++,q++)
if (*p==*q) return p-s;
return -1;
}
/* Step 4: Get rid of i and j. You're not using them any more. */
int f4 (char s[], char t[]) {
char *p, *q;
for (p=s; *p !='\0'; p++)
for (q=t; *q !='\0'; q++)
if (*p==*q) return p-s;
return -1;
}