c语言strcmp函数的使用

 这个函数接口实在简单,直接写几个实例了解如何使用就行了

// `strcmp` 是 C 标准库中的字符串比较函数,用于比较两个字符串是否相同。其原型为:
// int strcmp(const char *s1, const char *s2);
// 其中,`s1` 和 `s2` 分别指向需要进行比较的两个字符串。
// 函数返回值是一个整型,用于表示两个字符串的大小关系。
// 如果 `s1` 比 `s2` “小”,则返回值为负数;
// 如果 `s1` 比 `s2` “大”,则返回值为正数;
// 如果两个字符串相等,则返回值为 0。

// 实例1. 比较两个固定字符串是否相等
// 该代码比较了两个固定字符串 "hello" 和 "world" 是否相等。
// `strcmp` 函数返回非 0 值,因此打印的结果是 "hello != world"。
#include <stdio.h>
#include <string.h>

int main()
{
    char s1[] = "hello";
    char s2[] = "world";
    int result = strcmp(s1, s2);
    if (result < 0) {
        printf("%s < %s\n", s1, s2);
    } else if (result == 0) {
        printf("%s == %s\n", s1, s2);
    } else {
        printf("%s > %s\n", s1, s2);
    }
    return 0;
}

// strcmp实例2. 比较两个用户输入的字符串是否相等
// 该代码要求用户输入两个字符串,然后比较它们是否相等。
#include <stdio.h>
#include <string.h>

int main() {
    char s1[20];
    char s2[20];
    printf("Enter string1: ");
    scanf("%s", s1);
    printf("Enter string2: ");
    scanf("%s", s2);
    int result = strcmp(s1, s2);
    if (result < 0) {
        printf("%s < %s\n", s1, s2);
    } else if (result == 0) {
        printf("%s == %s\n", s1, s2);
    } else {
        printf("%s > %s\n", s1, s2);
    }
    return 0;
}

// strcmp实例3. 使用 `strcmp` 函数对字符串进行排序
// 该代码通过 `qsort` 函数对一个字符串数组进行排序并输出。
// 其中,比较函数 `cmp` 对应上面讲述的 `strcmp` 函数。
// 其余部分的主要作用是动态分配内存并释放相应的资源。
// 运行该程序时,需要输入需要排序的字符串个数和每个字符串本身,最后按照字典序输出排序后的结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *a, const void *b)
{
    return strcmp(*(char **)a, *(char **)b);
}

int main()
{
    int n, i;
    scanf("%d", &n);
    char **strs = (char **) malloc(n * sizeof(char *));
    for (i = 0; i < n; ++i) {
        char *str = (char *) malloc(16 * sizeof(char));
        scanf("%s", str);
        strs[i] = str;
    }
    qsort(strs, n, sizeof(char *), cmp);
    printf("%s", strs[0]);
    for (i = 1; i < n; ++i) {
        printf(" %s", strs[i]);
    }
    printf("\n");
    for (i = 0; i < n; ++i) {
        free(strs[i]);
    }
    free(strs);
    return 0;
}

实现一个自定义的模拟strcmp函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值