字符串比较函数strcmp_C程序使用strcmp()函数比较字符串

字符串比较函数strcmp

Given two strings and we have to compare them using strcmp() function in C language.

给定两个字符串,我们必须使用C语言的strcmp()函数进行比较。

C语言strcmp()函数 (C language strcmp() function)

strcmp() function is used to compare two stings, it checks whether two strings are equal or not.

strcmp()函数用于比较两个字符串,它检查两个字符串是否相等。

strcmp() function checks each character of both the strings one by one and calculate the difference of the ASCII value of the both of the characters. This process continues until a difference of non-zero occurs or a \0 character is reached.

strcmp()函数一个接一个地检查两个字符串的每个字符,并计算两个字符的ASCII值之差。 此过程一直持续到出现非零的差异或达到\ 0字符为止。

Return value/result of strcmp() function:

返回值/ strcmp()函数的结果:

  • 0 : If both the strings are equal

    0 :如果两个字符串相等

  • Negative : If the ASCII value of first unmatched character of first string is smaller than the second string

    负数 :如果第一个字符串的第一个不匹配字符的ASCII值小于第二个字符串

  • Positive : If the ASCII value of first unmatched character of first character is greater than the second string

    正数 :如果第一个字符的第一个不匹配字符的ASCII值大于第二个字符串

C程序/ strcmp()函数的示例 (C program/example for strcmp() function)

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

int main(){
    char str1[] = "Includehelp", str2[] = "includehelp", str3[] = "Includehelp";
    int res = 0, cmp = 0;

    // Compares string1 and string2 and return the difference
    // of first unmatched character in both of the strings
    // unless a '\0'(null) character is reached.
    res = strcmp(str1, str2);

    if (res == 0)
        printf("\n %s and %s are equal\n\n", str1, str2);
    else
        printf("\n %s and %s are not equal\n\n", str1, str2);

    // Compares string1 and string3 and return the difference
    // of first unmatched character in both of the strings
    // unless a '\0'(null) character is reached.
    cmp = strcmp(str1, str3);

    if (cmp == 0)
        printf(" %s and %s are equal\n\n", str1, str3);
    else
        printf(" %s and %s are not equal\n\n", str1, str3);

    return 0;
}

Output

输出量

Includehelp and includehelp are not equal

 Includehelp and Includehelp are equal


翻译自: https://www.includehelp.com/c-programs/compare-strings-using-strcmp-function.aspx

字符串比较函数strcmp

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值