プログラミング言語 C 2.5


文字列 s2の任意の文字と等しい文字列 s1の最初の文字位置を返す
any(s1, s2)を書けという問題。一致しない場合は -1を返す。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

static int any(char *s1, char *s2);
static void test_any();

int
main(int argc, char **argv)
{
     int answer;

     if (argc != 3) {
          fprintf(stderr, "Invalid argument number\n");
          exit(EXIT_FAILURE);
     }

     test_any();
     answer = any(argv[1], argv[2]);

     if (answer != -1) {
          printf("%sの %d番目に見つかりました.\n", argv[1], answer);
     }
     else {
          printf("見つかりませんでした\n");
     }

     return 0;
}

static void
test_any()
{
     assert(any("", "") == -1);
     assert(any("a", "a") == 0);
     assert(any("abcde", "edc") == 2);
     assert(any("abcde", "ab") == 0);
     assert(any("abcde", "fghij") == -1);
}

static int
any (char *s1, char *s2)
{
     int i, j;
     int min_pos;

     min_pos = strlen(s1);

     for (i = 0, j = 0; s1[i] != '\0'; i++) {

          for (j = 0; s2[j] != '\0'; j++) {
               if (s1[i] == s2[j]) {
                    min_pos = (min_pos < i) ? min_pos : i;
               }
          }
     }

     /* if elements of s1 do not match any elements of s2
        return -1 */
     return (min_pos == strlen(s1) ? -1 : min_pos);
}