C strcmp() function
C strcmp() function - compare two strings
The strcmp() function is used to compare two given strings.
Syntax:
int strcmp(const char *string1, const char *string2)
Parameters:
Name | Description | Required /Optional |
---|---|---|
string1 | Null-terminated strings to compare. | Required |
string2 | Null-terminated strings to compare. | Required |
Return value from strcmp()
Name | Value |
---|---|
string1 is less than string2 | < 0 |
string1 is identical to string2 | 0 |
string1 is greater than string2 | >0 |
Example: strcmp() function
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "1234567890";
char str2[] = "1234567890";
int result;
printf("Original text:");
printf("\n%s",str1);
printf("\n%s",str2);
printf( "\nCompare the said two strings:");
result = strcmp(str1, str2);
if( result < 0 )
printf( "\nFirst is less than second.\n" );
else if( result == 0 )
printf( "\nFirst is equal to second.\n" );
else
printf( "\nFirst is greater than second.\n" );
char str3[] = "12345678901";
char str4[] = "12345678900";
printf("\nOriginal text:");
printf("\n%s",str3);
printf("\n%s",str4);
printf( "\nCompare the said two strings:");
result = strcmp(str3, str4);
if( result < 0 )
printf( "\nFirst is less than second.\n");
else if( result == 0 )
printf( "\nFirst is equal to second.\n");
else
printf( "\nFirst is greater than second.\n");
char str5[] = "12345678901100345678";
char str6[] = "12345678901297650033";
printf("\nOriginal text:");
printf("\n%s",str5);
printf("\n%s",str6);
result = strcmp(str5, str6);
if( result < 0 )
printf( "\nFirst is less than second.\n");
else if( result == 0 )
printf( "\nFirst is equal to second.\n");
else
printf( "\nFirst is greater than second.\n");
return 0;
}
Output:
Original text: 1234567890 1234567890 Compare the said two strings: First is equal to second. Original text: 12345678901 12345678900 Compare the said two strings: First is greater than second. Original text: 12345678901100345678 12345678901297650033 First is less than second.
C Programming Code Editor:
Previous C Programming: C strchr()
Next C Programming:C strncmp()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics