BohYoh.comトップページへ

C言語によるアルゴリズムとデータ構造

戻る  

演習8-6の解答

 strncmp 関数と同じ動作をする以下の関数を作成せよ。
  int str_ncmp (const char *s1 , const char *s2 , size_t n);

/* 演習8-6 文字列の先頭n文字を比較(標準ライブラリstrncmp関数と同じ仕様) */ #include <stdio.h> #include <string.h> /*--- 文字列s1とs2の先頭n文字を比較 ---*/ int str_ncmp(const char *s1, const char *s2, size_t n) { while (n && *s1 && *s2) { if (*s1 != *s2) /* 等しくない */ return ((unsigned char)*s1 - (unsigned char)*s2); s1++; s2++; n--; } if (!n) return (0); if (*s1) return (1); return (-1); } int main(void) { int cmp1, cmp2; char st[100]; puts("\"ABCDE\"と先頭3文字を比較します。"); puts("\"XXXXX\"で終了します。"); while (1) { printf("\n文字列st:"); scanf("%s", st); if (strcmp(st, "XXXXX") == 0) break; printf("strncmp(\"ABCDE\", st, 3) = %d\n", strncmp("ABCDE", st, 3)); } return (0); }


戻る