CSM217: C for Computer Scientists

Lecture 3: Exercise 2: Solution


#include <stdio.h>

int any(char [], char []);

main() {
 char s1[] = "This is a string";
 char s2[] = "xyT zig";

 printf("Searching for one of \"%s\" in the string \"%s\"\n", s2, s1);
 printf("Located in position: %d\n", any(s1, s2));
}

int any(char s1[], char s2[]) {
 int pos = -1;
 int i, j;
 
 for (i=0; s2[i] != '\0'; i++) { // process char to find
  for (j = 0; s1[j] != '\0'; j++) { // process original string
   if (s2[i] == s1[j]) { // we've found a match!
    if (pos == -1 || j < pos) { // if first match or earlier match
     pos = j;
    }
   }
  }
 }
 return pos; // remember, first location in an array is 0!
}