私が先日作っていたプログラムの一部を例にします。これはHTMLのうちの一部を受け取って、それを適当に加工してコンソールに出力するためのものです。
char last = 0;
while (*p != '\0') {
if (*p == '<') {
if (strncmp(p, "<br />", 6) == 0) { p += 6; putchar('\n'); continue; }
if (strncmp(p, "<strong>", 8) == 0) { p += 8; continue; }
if (strncmp(p, "</strong>", 9) == 0) { p += 9; continue; }
if (strncmp(p, "<div>", 5) == 0) { p += 5; continue; }
if (strncmp(p, "</div>", 6) == 0) { p += 6; continue; }
if (strncmp(p, "<h3>", 4) == 0) { p += 4; putchar('\n'); continue; }
if (strncmp(p, "</h3>", 5) == 0) { p += 5; putchar('\n'); continue; }
(似たような処理がまだたくさん続くが面倒なので省略)
}
if (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t') {
p++;
if (last != ' ')
putchar(last = ' ');
} else
putchar(last = *p++);
}
まあ普通のプログラムです。でももしstrncmpSkip()という関数を作って以下のように書き換えたらどうでしょうか?
int strncmpSkip(const char **p, const char *s)
{
int l = strlen(s);
if (strncmp(*p, s, l) == 0) {
*p += l;
return 1;
}
return 0;
}
char last = 0;
while (*p != '\0') {
if (*p == '<') {
if (strncmpSkip(&p, "<br />")) { putchar('\n'); continue; }
if (strncmpSkip(&p, "<strong>")) continue;
if (strncmpSkip(&p, "</strong>")) continue;
if (strncmpSkip(&p, "<div>")) continue;
if (strncmpSkip(&p, "</div>")) continue;
if (strncmpSkip(&p, "<h3>")) { putchar('\n'); continue; }
if (strncmpSkip(&p, "</h3>")) { putchar('\n'); continue; }
(似たような処理がまだたくさん続くが面倒なので省略)
}
if (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t') {
p++;
if (last != ' ')
putchar(last = ' ');
} else
putchar(last = *p++);
}