開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第5章(ポインタと配列)、5.5(文字ポインタと関数)、演習5-5を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 5-5.
コード
sample.c
#include <stdio.h> #define SIZE 1000 void my_strncpy(char *s, char *t, int n); void my_strncat(char *s, char *t, int n); int my_strncmp(char *s, char *t, int n); int main() { char s[SIZE], s1[SIZE]; char t[] = "Hello, World!"; int i; printf("strncpy\n"); printf("%s\n", t); for (i = 0; i < 15; i++) { my_strncpy(s, t, i); printf("%s\n", s); } printf("strncat\n"); for (i = 0; i < 15; i++) { s[0] = '\0'; my_strncat(s, t, i); printf("%s\n", s); } printf("strncmp\n"); for (i = 0; i < 5; i++) printf("%d\n", my_strncmp("", "", i)); for (i = 0; i <= 6; i++) printf("%d\n", my_strncmp("abcde", "", i)); for (i = 0; i <= 6; i++) printf("%d\n", my_strncmp("", "abcde", i)); for (i = 0; i <= 6; i++) printf("%d\n", my_strncmp("abcde", "ab", i)); for (i = 0; i <= 6; i++) printf("%d\n", my_strncmp("ab", "abcde", i)); return 0; } void my_strncpy(char *s, char *t, int n) { while (n-- > 0 && (*s++ = *t++)) ; if (n < 0) *s = '\0'; } void my_strncat(char *s, char *t, int n) { while (*s != '\0') s++; while (n-- > 0 && (*s++ = *t++)) ; if (n < 0) *s = '\0'; } int my_strncmp(char *s, char *t, int n) { for (; *s == *t; s++, t++) if (*s == '\0' || --n <= 0) return 0; return *s - *t; }
入出力結果(Terminal)
$ ./a.out strncpy Hello, World! H He Hel Hell Hello Hello, Hello, Hello, W Hello, Wo Hello, Wor Hello, Worl Hello, World Hello, World! Hello, World! strncat H He Hel Hell Hello Hello, Hello, Hello, W Hello, Wo Hello, Wor Hello, Worl Hello, World Hello, World! Hello, World! strncmp 0 0 0 0 0 97 97 97 97 97 97 97 -97 -97 -97 -97 -97 -97 -97 0 0 0 99 99 99 99 0 0 0 -99 -99 -99 -99 $
0 コメント:
コメントを投稿