C言語 文字列比較 strncmp

strncmp()を使った文字列の比較。wavヘッダを読み込むときに頻繁に利用するので、改めて基本的な動作を確認。

文字列の比較

#include <stdio.h>
#include <string.h>

void cmp(char *str1, char *str2) {
 int bytecount = 4;
 /* 文字列が等しいならば 0 (byte数を指定可) */
 if (strncmp(str1, str2, bytecount) == 0) {
    printf("The strings are identical."
           "\"%s\" \"%s\" %d-bytes",
           str1, str2, bytecount);
 } else {
    printf("The strings are different."
           " \"%s\" \"%s\" %d-bytes",
           str1, str2, bytecount);
 }
}

int main(void) {
 char str[][8] = {"image", "imagine"};
 cmp(str[0], str[1]);
 return 0;
}
頭から4byte分同じであれば、5byte以降は違っても同じ文字列とみなすプログラム。
The strings are identical."image" "imagine" 4-bytes


C言語 ANSI C89 Meadow & MinGW GCC 目次