開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第4章(関数とプログラム構造)4.1(関数についての基本事項)の演習4-1を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 4-1.
コード
sample.c
#include <stdio.h>
#define MAXLINE 1000
int my_getline(char s[], int);
int strrindex(char s[], char t[]);
int main()
{
char line[MAXLINE], pattern[] = "char";
int found, i;
found = 0;
while (my_getline(line, MAXLINE) > 0) {
if ((i = strrindex(line, pattern)) > 0) {
found++;
}
printf("%d: %s", i, line);
}
printf("\nfound: %d\n", found);
return 0;
}
int strrindex(char s[], char t[])
{
int i, j, k, l;
for (i = 0; s[i] != '\0'; i++)
;
for (j = 0; t[j] != '\0'; j++)
;
k = i - j;
while (k >= 0) {
for (l = 0; t[l] != '\0' && s[k] == t[l]; k++, l++)
;
if (t[l] == '\0') {
return i - j;
}
i--;
k = i - j;
}
return -1;
}
int my_getline(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n') {
s[i++] = c;
}
if (c == '\n') {
s[i++] = c;
}
s[i] = '\0';
return i;
}
入出力結果(Terminal)
$ ./a.out < sample.c
-1: #include <stdio.h>
-1: #define MAXLINE 1000
-1:
15: int my_getline(char s[], int);
24: int strrindex(char s[], char t[]);
-1:
-1: int main()
-1: {
37: char line[MAXLINE], pattern[] = "char";
-1: int found, i;
-1: found = 0;
-1: while (my_getline(line, MAXLINE) > 0) {
-1: if ((i = strrindex(line, pattern)) > 0) {
-1: found++;
-1: }
-1: printf("%d: %s", i, line);
-1: }
-1: printf("\nfound: %d\n", found);
-1: return 0;
-1: }
-1:
24: int strrindex(char s[], char t[])
-1: {
-1: int i, j, k, l;
-1:
-1: for (i = 0; s[i] != '\0'; i++)
-1: ;
-1: for (j = 0; t[j] != '\0'; j++)
-1: ;
-1: k = i - j;
-1: while (k >= 0) {
-1: for (l = 0; t[l] != '\0' && s[k] == t[l]; k++, l++)
-1: ;
-1: if (t[l] == '\0') {
-1: return i - j;
-1: }
-1: i--;
-1: k = i - j;
-1: }
-1: return -1;
-1: }
-1:
15: int my_getline(char s[], int lim)
-1: {
-1: int c, i;
-1:
-1: i = 0;
32: while (--lim > 0 && (c = getchar()) != EOF && c != '\n') {
-1: s[i++] = c;
-1: }
-1: if (c == '\n') {
-1: s[i++] = c;
-1: }
-1: s[i] = '\0';
-1: return i;
-1: }
found: 6
$
0 コメント:
コメントを投稿