C 라이브러리 함수 int strcmp(const char *str1, const char *str2) str1이 가리키는 문자열을 비교합니다. str2가 가리키는 문자열로 .
문자 배열을 문자열이라고 합니다.
선언
다음은 배열에 대한 선언입니다 -
char stringname [size];
예를 들어 - char string[50]; 길이 50자의 문자열
초기화
- 단일 문자 상수 사용 -
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- 문자열 상수 사용하기 -
char string[10] = "Hello":;
액세스 − '\0'이 나타날 때까지 문자열에 액세스하는 데 사용되는 제어 문자열 "%s"가 있습니다.
strcmp() 함수
-
이 함수는 두 문자열을 비교합니다.
-
두 문자열에서 일치하지 않는 처음 두 문자의 ASCII 차이를 반환합니다.
문자열 비교
구문은 다음과 같습니다 -
int strcmp (string1, string2);
차이가 0인 경우 ------ string1 =string2
차이가 양수인 경우 ------- string1> string2
차이가 음수인 경우 ------- string1
예시 프로그램
다음 프로그램은 strcmp() 함수의 사용법을 보여줍니다 -
#include<stdio.h> main ( ){ char a[50], b [50]; int d; printf ("enter 2 strings:\n"); scanf ("%s %s", a,b); d = strcmp (a,b); if (d==0) printf("%s is equal to %s", a,b); else if (d>0) printf("%s is greater than %s",a,b); else if (d<0) printf("%s is less than %s", a,b); }
출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
enter 2 strings: bhanu priya bhanu is less than priya
strcmp()에 대한 다른 예를 살펴보겠습니다.
다음은 strcmp 라이브러리 함수를 사용하여 두 문자열을 비교하는 C 프로그램입니다 -
예시
#include<stdio.h> #include<string.h> void main(){ //Declaring two strings// char string1[25],string2[25]; int value; //Reading string 1 and String 2// printf("Enter String 1: "); gets(string1); printf("Enter String 2: "); gets(string2); //Comparing using library function// value = strcmp(string1,string2); //If conditions// if(value==0){ printf("%s is same as %s",string1,string2); } else if(value>0){ printf("%s is greater than %s",string1,string2); } else{ printf("%s is less than %s",string1,string2); } }
출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Enter String 1: Tutorials Enter String 2: Point Tutorials is greater than Point