S16 Answer


/* Puzzle S16 — Find the first character in one string that is also in another  */
#include <stdio.h>
#include <stdlib.h>

/* Find the first character in *str that is also in *set. */
/* Return its index */
int findCstring( char const *str, char const *set)
{
  char const *p, *s;

  for ( p=str; *p; p++ )
    for ( s=set; *s; s++)
      if ( *s == *p ) return p-str;

  return -1;
}

int main(int argc, char *argv[])
{
  char *trials[][2] =
  {
    {"abcdef", "a"},
    {"abcdef", "xyza"},
    {"abcdef", "f"},
    {"abcdef", "zxyf"},
    {"abcdef", "zxfy"},
    {"abcdef", "c"},
    {"abcdef", "xyzc"},
    {"abcdef", "cxyz"},
    {"abcdef", "xxcyz"},
    {"abbccddeef", "xyzfzz"},
    {"abcdefg", "gfedec"},
    {"small", "xxxxxxxxxxxxmxxxxxxxxx"},
    {"green", "apple"},
    {"apple", ""},
    {"", "rats"},
    {"",""}
  };

  int j, loc ;
  for ( j=0; j<sizeof(trials)/sizeof(trials[0]); j++ )
  {
    loc = findCstring( trials[j][0], trials[j][1] );
    if ( loc != -1 )
      printf("Found %c from %s at index %d in %s\n",
        trials[j][0][loc], trials[j][1], loc, trials[j][0] );
    else
      printf("Found no character from %s in %s\n",
        trials[j][1], trials[j][0] );
  }

  system("PAUSE");
  return 0;
}

Comments: