我要评分
获取效率
正确性
完整性
易理解

strcmp

Function Usage

Compares the lexicographical order of two strings character by character until a difference is found or the string terminator (\0) is reached. The returned result can be a positive or negative value or 0.

Function Syntax

int strcmp(const char *str1, const char *str2);

Parameters

Parameter

Description

Value Range

Input/Output

str1

Pointer to the first character string.

Non-null pointer, pointing to a character string that ends with \0.

Input

str2

Pointer to the second character string.

Non-null pointer, pointing to a character string that ends with \0.

Input

Return Value

  • Success: An integer is returned.
    • If str1 is smaller than str2, a negative value is returned.
    • If str1 is equal to str2, 0 is returned.
    • If str1 is greater than str2, a positive value is returned.
  • Failure: See those of open source glibc. No other exception values will be returned.

Characters are case sensitive. Therefore, the character strings "abc" and "ABC" are different.

Example

#include <stdio.h>
#include <string.h>

int main() {
    const char *str1 = "apple";
    const char *str2 = "banana";
    const char *str3 = "apple";
    const char *str4 = "Banana";
    const char *str5 = "APPLE";
    int result1 = strcmp(str1, str2);
    printf("apple compared to banana: %d\n", result1);
    int result2 = strcmp(str1, str3);
    printf("apple compared to apple: %d\n", result2);
    int result3 = strcmp(str1, str4);
    printf("apple compared to Banana: %d\n", result3);
    int result4 = strcmp(str5, str1);
    printf("APPLE compared to apple: %d\n", result4);

    return 0;
}

Output:

apple compared to banana: -60
apple compared to apple: 0
apple compared to Banana: 124
APPLE compared to apple: -128