strncmp 比较某一长度的两个字符串

头文件

#include <string.h>

语法

int strncmp( const char *str1, const char *str2, size_t count );

功能

比较字符串str1 和 str2中至多count个字符。返回值如下:

  • 小于0,则 str1 小于 str2

  • 等于0,则 str1 等于 str2

  • 大于0,则 str1 大于 str2 

如果参数中任一字符串长度小于 count,那么当比较到第一个空值结束符时,就结束处理。

示例

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

int  main(void)

{
    char *buf1 = "aaabbb", *buf2 = "bbbccc", *buf3 = "ccc";
    int ptr;

    ptr = strncmp(buf2,buf1,3);
    if (ptr > 0)
    {
        printf("buf2 is greater than buf1\n");
    }
    else
    {

        printf("buf2 is less than buf1\n");
    }

    ptr = strncmp(buf2,buf3,3);
    if (ptr > 0)
    {
        printf("buf2 is greater than buf3\n");
    }
    else
    {
        printf("buf2 is less than buf3\n");
    }

    return(0);
}

输出结果:

buf2 is greater than buf1
buf2 is less than buf3
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号