C言語のstrncmp関数の使い方は?
C言語のstrncmp関数は、2つの文字列の先頭からn文字までが等しいかどうかを比較する関数です。宣言は以下の通りです。
int strncmp(const char* str1, const char* str2, size_t n);
参数说明:
- 比較する最初の文字列
- 比較する2番目の文字列
- 文字数の比較
戻り値:
- str1とstr2の先頭n文字が等しければ0を返す
- str1 が str2 より小さい場合は負の値を返す
- str1がstr2より大きいときは正の値を返します
ただし、比較する文字数nは、二つの文字列より短くなければいけないです。さもないと、配列の範囲を越えてしまう可能性があります。
以下に、strncmp関数の使用例を示します。
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hel";
int result = strncmp(str1, str2, 3);
if (result == 0) {
printf("The first 3 characters of str1 and str2 are the same.\n");
} else if (result < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
return 0;
}
このような結果が生じる
The first 3 characters of str1 and str2 are the same.