演習 2-5

無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。

演習 2-5
文字列 s2 の任意の文字と等しい文字列 s1 の最初の文字位置を返す関数 any(s1, s2) を書け。ただし、一致する文字がなければ -1 を返す。(標準ライブラリ関数 strpbrk は同じ働きをもつが、その位置へのポインタを返す。)


Exercise 2-5
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.)

ちょっと使い勝手の分からない関数。


先日のようなゼロとオーの打ち間違いで悩まないように、 Consolas フォントとモトヤシーダのFontLinkの設定をした。
Consolas は BOφWY みたいなゼロが表示されるので、ゼロとオーの区別がしやすい)


参考にしたサイト:
http://overlasting.dyndns.org/2006-11-07-3.html


そしたら Putty 経由の coLinux で動く Emacs が、ものすごく見やすくなった。
調べてみて分かったけど、どうも3年遅れているな。俺は。

#include <stdio.h>

/* Answer */
int any(const char s1[], const char s2[])
{
  int i, j;

  for (i = 0; s1[i] != '\0'; i++) {
    for (j = 0; s2[j] != s1[i] && s2[j] != '\0'; j++)
      ;
    if (s2[j] != '\0') return i;
  }
  return -1;

}


int main(void)
{
  //                     1         2         3
  //           01234567890123456789012345678901234
  char s1[] = "BRIAN W.KERNIGHAN / DENNIS M.RITCHE";

  printf("[%s]\n", s1);

  printf("[%d]\n", any(s1, "BOMB"));
  printf("[%d]\n", any(s1, "POW"));
  printf("[%d]\n", any(s1, "CX"));
  printf("[%d]\n", any(s1, "ZOO"));
  printf("[%d]\n", any(s1, "\0"));

  return 0;
}