c语言strcmp函数用法_strcmp()C库函数用法和示例

c语言strcmp函数用法_strcmp()C库函数用法和示例_第1张图片

c语言strcmp函数用法

C programming standard library provides strcmp() function in order to compare two strings and return the results whether they are identical or different.

C编程标准库提供strcmp()函数,以便比较两个字符串并返回相同或不同的结果。

语法和参数 (Syntax and Parameters)

As stated previously strcmp() function takes two char array or string arguments.

如前所述,strcmp()函数采用两个char数组或字符串参数。

int strcmp (const char* str1, const char* str2);
  • const char* str1 is the first string or char array which will be compared the second one. const is mainly used to prevent given char array pointer to be changed.

    const char * str1是第一个字符串或char数组,将与第二个字符串或char数组进行比较。 const主要用于防止更改给定的char数组指针。
  • const char* str2 is the second string or char array which will be compared with the first one.

    const char * str2是第二个字符串或char数组,将与第一个比较。

返回值 (Return Values)

strcmp() function returns an int or integer type. We can get 3 types of return value that are explained below.

strcmp()函数返回一个int或整数类型。 我们可以得到以下三种返回值类型。

  • `0` is returned if both strings are identical, equal or the same.

    如果两个字符串相同,相等或相同,则返回“ 0”。
  • `Negative Integer` if the ASCII value of the first unmatched character is less then second

    “负整数”,如果第一个不匹配字符的ASCII值小于第二个字符
  • `Positive Integer` if the ASCII value of the first unmatched character is greater than second

    如果第一个不匹配字符的ASCII值大于第二个,则为“正整数”

比较两个字符串 (Compare Two Strings)

We can compare two strings which are expressed as char array in C programming language. We will compare strings “I love poftut.com” and “I loves poftut.com” .

我们可以比较两个用C编程语言表示为char数组的字符串。 我们将比较字符串“我爱poftut.com”和“我爱poftut.com”。

#include 
#include 

int main()
{
    char str1[] = "I love poftut.com", str2[] = "I loves poftut.com";
    int result;

    // comparing strings str1 and str2
    result = strcmp(str1, str2);
    printf("strcmp(str1, str2) = %d\n", result);

    return 0;
}

We will compile with gcc like below and then run the binary.

我们将使用下面的gcc进行编译,然后运行二进制文件。

你可能感兴趣的:(字符串,c++,c语言,指针,etl)