C语言 strncmp

C语言 strncmp

#include <string.h>
int strncmpconst char *s1, const char *s2, size_t n);

功能:比较 s1 和 s2 前n个字符的大小,比较的是字符ASCII码大小。

参数:

       s1:字符串1首地址
       s2:字符串2首地址
       n:指定比较字符串的数量

返回值:

       相等:0
       大于: > 0
       小于: < 0

案例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int mainvoid)
{
    char ch1[] = "hello world";
    char ch2[] = "hallo world";

    // 两个有限字符串比较
    int    value = strncmpch1, ch2);

    // 返回为1不相等
    printf"%d
", value);

    return 0;
}

strncmp 使用案例:使用函数

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

my_strncmpconst char *s1, const char *s2,  size_t n)
{
    for int i = 0; i < n && s1[i] && s2[i]; i++)
    {
        if s1[i] != s2[i])
        {
            return s1[i] > s2[i] ? 1 : -1;
        }
    }
    return 0;
}

int mainvoid)
{
    char ch1[] = "hello world";
    char ch2[] = "hallo world";

    // 两个字符串有限比较
    int    value = my_strncmpch1, ch2, 3);

    // 返回为1不相等
    printf"%d
", value);

    return 0;
}

strncmp 使用案例:创建函数

Published by

风君子

独自遨游何稽首 揭天掀地慰生平