「C言語」strcmp関数で文字列を比較するサンプル

構文
strcmp(str1, str2)
同じ文字列なら「0」を取得します。
サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
#include <string.h>
int main(void)
{
char cftA[20], cftB[20], cftC[20];
// 文字列コピー
strcpy(cftA, "BB00231");
strcpy(cftB, "AA0245");
strcpy(cftC, "AA0245");
printf("cftA = %s, cftB = %s, cftC = %s\n", cftA, cftB,cftC);
// 文字列を比較
printf("cftA cftB compare %d\n", strcmp(cftA, cftB));
printf("cftA cftC compare %d\n", strcmp(cftA, cftC));
printf("cftC cftB compare %d\n", strcmp(cftC, cftB));
return 0;
}
#include <stdio.h> #include <string.h> int main(void) { char cftA[20], cftB[20], cftC[20]; // 文字列コピー strcpy(cftA, "BB00231"); strcpy(cftB, "AA0245"); strcpy(cftC, "AA0245"); printf("cftA = %s, cftB = %s, cftC = %s\n", cftA, cftB,cftC); // 文字列を比較 printf("cftA cftB compare %d\n", strcmp(cftA, cftB)); printf("cftA cftC compare %d\n", strcmp(cftA, cftC)); printf("cftC cftB compare %d\n", strcmp(cftC, cftB)); return 0; }
#include <stdio.h>
#include <string.h>

int main(void)
{
  char cftA[20], cftB[20], cftC[20];

  // 文字列コピー
  strcpy(cftA, "BB00231");
  strcpy(cftB, "AA0245");
  strcpy(cftC, "AA0245");
  printf("cftA = %s, cftB = %s, cftC = %s\n", cftA, cftB,cftC);

  // 文字列を比較
  printf("cftA cftB compare %d\n", strcmp(cftA, cftB));
  printf("cftA cftC compare %d\n", strcmp(cftA, cftC));
  printf("cftC cftB compare %d\n", strcmp(cftC, cftB));

  return 0;
}

実行結果
cftA = BB00231, cftB = AA0245, cftC = AA0245
cftA cftB compare 1
cftA cftC compare 1
cftC cftB compare 0

C言語

Posted by arkgame