Puzzle S16

Find the first character in one string that is also in another

[H-5]Write function that returns a pointer to the first character in a string that is a member of a second string. Here is a prototype for the function:

int findCstring( char const *str, char const *set);

The function returns an index to the first character in str that is also in set. For example,

int findCstring(  "spaceship", "bcde" )

returns a the value 3, which is the index of the 'c' in the first string. Remember that indexes for strings start at zero. If none of the characters in set are found in the string, return -1. The set can have duplicated characters. If the set is empty, return -1. If the string is empty, return -1. Here is a testing program:

/* Puzzle S16 -- 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)
{
}

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] );
  }

  return 0;

This function is similar to the standard function strcspn() described in <strings.h> .



Answer         Next Page         Previous Page Home