Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 두 문자열이 같은지 확인하는 프로그램

<시간/>

두 개의 문자열 str1과 str2가 주어지면 두 문자열이 동일한지 여부를 확인해야 합니다. 우리에게 "hello"와 "hello"라는 두 개의 문자열이 주어지는 것처럼 동일하고 동일합니다.

"Hello" 및 "hello"와 같이 같아 보이지만 같지 않은 문자열이고 "World" 및 "World"와 같은 문자열은 동일합니다.

예시

Input: str1[] = {“Hello”}, str2[] = {“Hello”}
Output: Yes 2 strings are same
Input: str1[] = {“world”}, str2[] = {“World”}
Output: No, 2 strings are not same

아래에 사용된 접근 방식은 다음과 같습니다. -

strcmp(string2, string1)를 사용할 수 있습니다.

strcmp() 문자열 비교 함수는 "string.h" 헤더 파일의 내장 함수이며, 이 함수는 두 개의 매개변수(두 문자열 모두)를 받습니다. 이 함수는 두 문자열을 비교하여 두 문자열이 동일한지 확인하고 문자열에 변경 사항이 없으면 0을 반환하고 두 문자열이 같지 않으면 0이 아닌 값을 반환합니다. 이 함수는 대소문자를 구분하므로 두 문자열이 정확히 동일해야 합니다.

  • 그래서 우리는 두 개의 문자열을 입력으로 받을 것입니다.
  • strcmp()를 사용하고 두 문자열을 매개변수로 전달
  • 0을 반환하면 "예 2 문자열이 동일합니다"를 인쇄합니다.
  • 그렇지 않으면 "아니요, 2개의 문자열이 동일하지 않습니다."라고 출력합니다.

알고리즘

Start
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize 2 strings string1[] and string2[]
   Step 2-> If strcmp(string1, string2) == 0 then,
      Print "Yes 2 strings are same\n"
   Step 3-> else
      Print "No, 2 strings are not same\n"
Stop

예시

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
   char string1[] = {"tutorials point"};
   char string2[] = {"tutorials point"};
   //using function strcmp() to compare the two strings
   if (strcmp(string1, string2) == 0)
      printf("Yes 2 strings are same\n");
   else
      printf("No, 2 strings are not same\n" );
      return 0;
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다 -

Yes 2 strings are same