C 言語での char 変数の比較
Satishkumar Bharadwaj
2023年1月30日
2020年12月21日
C
C Char

このチュートリアルでは、C 言語で char 変数を比較する方法を紹介します。char 変数は、0 から 255 までの 8 ビットの整数値です。ここでは、0
は C-null 文字を表し、255 は空の記号を表します。
C 言語で比較演算子を使って文字を比較する
char 変数は独自の ASCII 値を持っています。そのため、文字は ASCII 値に従って比較されます。完全なプログラムは以下の通りです。
#include<stdio.h>
int main(void)
{
char firstCharValue='m';
char secondCharValue='n';
if(firstCharValue < secondCharValue)
printf("%c is smaller than %c.", firstCharValue, secondCharValue);
if(firstCharValue > secondCharValue)
printf("%c is smaller than %c.", firstCharValue, secondCharValue);
if(firstCharValue == secondCharValue)
printf("%c is equal to %c.", firstCharValue, secondCharValue);
return 0;
}
出力:
m is smaller than n.
C 言語で strcmp()
関数を用いた C 言語での文字の比較
関数 strcmp()
は string
ヘッダファイルで定義されており、2つの文字列を 1 文字ずつ比較するために用いられます。
両方の文字列の最初の文字が等しい場合、2つの文字列の次の文字が比較されます。両文字列の対応する文字が異なるか、ヌル文字 '\0'
に達するまで比較を続きます。
関数 strcmp()
の構文は以下の通りです。
int strcmp (const char* firstStringValue, const char* secondStringValue);
- 2つの文字列が等しいか同一であれば、
0
を返します。 - 最初の文字の ASCII 値が 2 番目の文字より大きい場合は、正の整数値を返します。
- 最初の一致しない文字の ASCII 値が 2 番目の文字より小さい場合は、負の整数値を返します。
2つの文字列を比較する完全なプログラムは以下の通りです。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
char firstString= "b", secondString= "b",thirdString= "B";
int result;
result= strcmp(&firstString, &secondString);
printf("strcmp(firstString, secondString) = %d\n", result);
result = strcmp(&firstString, &thirdString);
printf("strcmp(firstString,thirdString) = %d\n", result);
return 0;
}
出力:
strcmp(firstString, secondString) = 0
strcmp(firstString, thirdString) = 1