Page 48
Write the function any(s1,s2)
, which returns the first location in the string s1
where any character from the string s2
occurs, or -1
if s1
contains no
characters from s2
. (The standard library function strpbrk
does the same job but
returns a pointer to the location.)
#include <stdio.h>
#include <stdbool.h>
int any(char s1[], char s2[])
{
int i, j, k;
int num_unique;
bool found;
/* Reduce s2 to unique characters */
for (i = num_unique = 0; s2[i] != '\0'; i++) {
found = false;
for (j = 0; j < num_unique; j++) {
if (s2[j] == s2[i]) {
found = true;
break;
}
}
if (!found) {
s2[num_unique++] = s2[i];
}
}
s2[num_unique] = '\0';
/* Eliminate from s1 all found in s2 */
for (i = j = 0; s1[i] != '\0'; i++) {
found = false;
for (k = 0; k < num_unique; k++) {
if (s1[i] == s2[k]) {
return i;
}
}
}
return -1;
}
int main()
{
char s1[] = "abcdefg";
char s2[] = "defghij";
printf("%d", any(s1, s2));
}