開発環境
- OS: macOS High Sierra - Apple
- Text Editor: Emacs
- コンパイラー: LLVM/Clang, GCC(gcc)
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数 - 関数を最大限に活用する)、エクササイズ(p. 321)を取り組んでみる。
エクササイズ(p. 321)
Makefile
CC = cc all: sample run sample: sample.c $(CC) sample.c -o sample run: sample ./sample
コード
#include <stdio.h>
#include <string.h> // strstr
typedef int (*fn_type)(char *s);
int NUM_ADS = 7;
char *ADS[] = {"William: SBM GSOH likes sports, TV, dining",
"Matt: SWM NS likes art, movies, theater",
"Luis: SLM ND likes books, theater, art",
"Mike: DWM DS likes trucks, sports and bieber",
"Peter: SAM likes chess, working out and art",
"Josh: SJM likes sports, movies and theater",
"Jed: DBM likes theater, books and dining"};
int sports_or_workout(char *s) {
return strstr(s, "sports") || strstr(s, "working");
}
int ns_theater(char *s) { return strstr(s, "NS") && strstr(s, "theater"); }
int arts_theater_or_dining(char *s) {
return strstr(s, "art") || strstr(s, "theater") || strstr(s, "dining");
}
fn_type matches[] = {sports_or_workout, ns_theater, arts_theater_or_dining,
NULL};
char *names[] = {"sports or workout", "ns theater", "arts theater or dining",
NULL};
void find(fn_type match) {
puts("検索結果:");
puts("--------------------------------------------------");
for (int i = 0; i < NUM_ADS; i++) {
if (match(ADS[i])) {
puts(ADS[i]);
}
}
puts("--------------------------------------------------");
}
int main() {
for (size_t i = 0; matches[i] != NULL; i++) {
puts(names[i]);
find(matches[i]);
}
}
入出力結果(Terminal)
$ make cc sample.c -o sample ./sample sports or workout 検索結果: -------------------------------------------------- William: SBM GSOH likes sports, TV, dining Mike: DWM DS likes trucks, sports and bieber Peter: SAM likes chess, working out and art Josh: SJM likes sports, movies and theater -------------------------------------------------- ns theater 検索結果: -------------------------------------------------- Matt: SWM NS likes art, movies, theater -------------------------------------------------- arts theater or dining 検索結果: -------------------------------------------------- William: SBM GSOH likes sports, TV, dining Matt: SWM NS likes art, movies, theater Luis: SLM ND likes books, theater, art Peter: SAM likes chess, working out and art Josh: SJM likes sports, movies and theater Jed: DBM likes theater, books and dining -------------------------------------------------- $
0 コメント:
コメントを投稿