再学C语言50:C库中的字符串函数(2)

本文介绍了C语言中用于字符串比较的strcmp()和strncmp()函数。strcmp()函数在两个字符串内容相同时返回0,按ASCII值逐字符比较,返回值取决于比较结果。而strncmp()函数允许指定比较的字符数,更可控。示例代码展示了这两个函数的使用和返回值情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、strcmp()函数

功能:对字符串内容进行比较,如果两个字符串参数相同,函数返回0

示例代码:

/* test of strcmp() function */
#include <stdio.h>
#include <string.h>

#define NAME "Forster"

int main(void)
{
    char arr[100];
    printf("guess my name:\n");
    gets(arr);
    while(strcmp(arr, NAME) != 0)
    {
        puts("Wrong, guess again:");
        gets(arr);
    }
    puts("Right!");
    
    return 0;
}

运行结果:

bf2954f51b9645058df5b57120aa3e10.png

strcmp()函数比较的是字符串,而不是数组;虽然arr占用100个内存单元,而“Forster”只占用8个内存单元(一个用来存放空字符),但是函数在比较时只看arr的第一个空字符之前的部分;因此,strcmp()函数可以用来比较存放在不同大小数组里的字符串


strcmp()函数的返回值:

strcmp()函数中,对两个字符串的所有字符按照顺序逐个比较,按照机器编码顺序进行比较,字符的比较根据的是它们的数字表示法,一般是ASCII值

如果第一个字符串在字母表中的顺序落后于第二个字符串,返回一个正数;如果第一个字符串在字母表中的顺序领先于第二个字符串,返回一个负数

确切的比较依赖于不同的C实现

示例代码:

/* test return value of strcmp() function */
#include <stdio.h>
#include <string.h>

int main(void)
{
    printf("strcmp(\"A\", \"A\") is ");
    printf("%d\n", strcmp("A", "A"));

    printf("strcmp(\"A\", \"B\") is ");
    printf("%d\n", strcmp("A", "B"));

    printf("strcmp(\"B\", \"A\") is ");
    printf("%d\n", strcmp("B", "A"));

    printf("strcmp(\"Apple\", \"A\") is ");
    printf("%d\n", strcmp("Apple", "A"));

    printf("strcmp(\"A\", \"Apple\") is ");
    printf("%d\n", strcmp("A", "Apple"));

    printf("strcmp(\"Apple\", \"Apples\") is ");
    printf("%d\n", strcmp("Apple", "Apples"));
    
    return 0;
}

运行结果:

8d3fdccc68794c76834a55e684ab3fe7.png


二、strncmp()函数

strcmp()函数比较字符串时,一直比较找到不同的相应字符,搜索可能要进行到字符串尾部

strncmp()函数比较字符串时,可以比较到字符串不同处,也可以比较完由第三个参数指定的字符数

示例代码:

/* test of strncmp() function */
#include <stdio.h>
#include <string.h>

int main(void)
{
    char arr1[] = "apple";
    char arr2[] = "apples";
    int res;

    printf("strint 1 is: %s\n", arr1);
    printf("string 2 is: %s\n", arr2);

    res = strcmp(arr1, arr2);
    printf("comparison result with strcmp() is %d\n", res);

    res = strncmp(arr1, arr2, 5);
    printf("comparison result with strncmp() is %d\n", res);

    return 0;
}

运行结果:

29d19a841a4d49b2916f21cfd85d290c.png

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Forster-C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值