😸

[C] strncmp 関数

に公開

機能

文字列を先頭から指定した文字数だけ比較する関数[1]

使用例

strcmp test と表示する

\n は改行を表す エスケープシーケンス[2]

コード

printf("strcmp test\n");
if (strncmp("apple", "apricot", 3) == 0) {
    printf("same\n");
} else {
    printf("not same\n");
}
全文
#include <stdio.h>
#include <string.h>
void main() {
    printf("strcmp test\n");
    if (strncmp("apple", "apricot", 3) == 0) {
        printf("same\n");
    } else {
        printf("not same\n");
    }
}

実行結果

strcmp test
same

Result: not same を変数から表示する

コード

char a[] = "orange";
char b[] = "orchard";
if (strncmp(a, b, 4) == 0) {
    printf("Result: same\n");
} else {
    printf("Result: not same\n");
}
全文
#include <stdio.h>
#include <string.h>
void main() {
    char a[] = "orange";
    char b[] = "orchard";
    if (strncmp(a, b, 4) == 0) {
        printf("Result: same\n");
    } else {
        printf("Result: not same\n");
    }
}

実行結果

Result: not same
脚注
  1. strcmpと異なり、最大n文字だけ比較する。等しい場合は0、違うと正負の値を返す。 ↩︎

  2. 改行やタブなど、画面に表示されない制御文字のこと。 ↩︎

Discussion