• C语言字符串比较详解:strcmp和strncmp函数的使用方法和规则


    字符串比较详解

    本篇博客将详细介绍C语言中的字符串比较函数strcmpstrncmp的使用方法和规则。首先,我们将分别介绍两个函数的基本用法和返回值的意义,然后通过具体的示例代码进行解释,最后给出相应的总结和注意事项。

    目录

    1. strcmp函数介绍
    2. strcmp函数示例
    3. strncmp函数介绍
    4. strncmp函数示例
    5. 总结与注意事项

    strcmp函数介绍

    strcmp函数用于比较两个字符串的大小关系。它按照从左到右的顺序逐个比较两个字符串中的字符,直到遇到第一个不同的字符,然后根据字符的ASCII码值来确定两个字符串的大小关系。

    比较规则如下:

    • 如果两个字符串完全相同,则返回0。
    • 如果两个字符串在某个位置上的字符不同,则返回第一个不同字符的ASCII码值差。
    • 如果其中一个字符串的长度比另一个短,但前部分字符都相同,则返回长度差。

    函数原型如下:

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

    strcmp函数示例

    下面通过具体的示例代码来演示strcmp函数的使用。

    #include 
    #include 
    
    int main() 
    {
        int result1 = strcmp("abc", "abc");
        printf("result1 = %d\n", result1);
        // 输出:result1 = 0,两个字符串相等
    
        int result2 = strcmp("abr", "abcde");
        printf("result2 = %d\n", result2);
        // 输出:result2 = 1,前者大于后者
    
        int result3 = strcmp("abcde", "ar");
        printf("result3 = %d\n", result3);
        // 输出:result3 = -1,前者小于后者
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    strncmp函数介绍

    strncmp函数与strcmp函数类似,但是它提供了比较前n个字符的功能。它按照从左到右的顺序逐个比较两个字符串中的字符,直到遇到第一个不同的字符或比较了n个字符为止。

    比较规则与strcmp函数相同。

    函数原型如下:

    int strncmp(const char *str1, const char *str2, size_t n);
    
    • 1

    strncmp函数示例

    下面通过具体的示例代码来演示strncmp函数的使用。

    #include 
    #include 
    
    int main() 
    {
        int result1 = strncmp("ab", "abc", 1);
        printf("result1 = %d\n", result1);
        // 输出:result1 = 0,两个字符串相等
    
        int result2 = strncmp("abr", "abcde", 2);
        printf("result2 = %d\n", result2);
        // 输出:result2 = 0,两个字符串相等
    
        int result3 = strncmp("abcde", "ar", 2);
        printf("result3 = %d\n", result3);
        // 输出:result3 = -1,前者小于后者
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    总结与注意事项

    • strcmp函数用于比较两个字符串的大小关系,返回值为0表示相等,正数表示前者大于后者,负数表示前者小于后者。
    • strncmp函数与strcmp函数类似,但比较前n个字符。
    • 在使用这两个函数时,需要注意字符串的长度和还未结束的情况。

    希望通过本篇博客能够帮助读者更好理解和使用C语言中的字符串比较函数。

  • 相关阅读:
    数学建模国赛模板
    Jsonp跨域的坑,关于jsonp你真的了解吗
    DRF: 序列化器、View、APIView、GenericAPIView、Mixin、ViewSet、ModelViewSet的源码解析
    2024Xtu程设第一次练习题解
    计算机竞赛 深度学习+opencv+python实现车道线检测 - 自动驾驶
    【北京迅为】《i.MX8MM嵌入式Linux开发指南》-第一篇 嵌入式Linux入门篇-第六章 Vim 编辑器的使用
    怎么用C++编一个回合制魂类游戏???(第一版)
    Spring Boot EasyPOI 使用指定模板导出Excel
    MPEG 解封装
    高并发-防止雪崩与穿透
  • 原文地址:https://blog.csdn.net/weixin_47712251/article/details/132868174