迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > C语言 >

C 语言中比较字符串

作者:迹忆客 最近更新:2023/03/30 浏览次数:

本文将介绍关于如何在 C 语言中比较字符串的多种方法。


使用 strcmp 函数比较字符串

strcmp 函数是定义在 <string.h> 头的标准库函数。C 风格的字符串只是以 0 符号结束的字符序列,所以函数必须对每个字符进行迭代比较。

strcmp 接受两个字符字符串,并返回整数来表示比较的结果。如果第一个字符串在词法上小于第二个字符串,则返回的数字为负数,如果后一个字符串小于前一个字符串,则返回的数字为正数,如果两个字符串相同,则返回的数字为 0

需要注意的是,在下面的例子中,我们将函数的返回值反转,并将其插入到 ?:条件语句中,打印相应的输出到控制台。

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

int main() {
    const char* str1 = "hello there 1";
    const char* str2 = "hello there 2";
    const char* str3 = "Hello there 2";

    !strcmp(str1, str2) ?
        printf("strings are equal\n") :
        printf("strings are not equal\n");

    !strcmp(str1, str3) ?
        printf("strings are equal\n") :
        printf("strings are not equal\n");

    exit(EXIT_SUCCESS);
}

输出:

strings are not equal
strings are not equal

使用 strncmp 函数只比较部分字符串

strncmp 是定义在 <string.h> 头文件中的另一个有用的函数,它可以用来只比较字符串开头的几个字符。

strncmp 的第三个参数为整数类型,用于指定两个字符串中要比较的字符数。该函数的返回值与 strcmp 返回的值类似。

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

int main() {
    const char* str1 = "hello there 1";
    const char* str2 = "hello there 2";

    !strncmp(str1, str2, 5) ?
        printf("strings are equal\n") :
        printf("strings are not equal\n");

    exit(EXIT_SUCCESS);
}

输出:

strings are equal

使用 strcasecmpstrncasecmp 函数比较忽略字母大小写的字符串

strcasecmp 函数的行为与 strcmp 函数类似,但它忽略字母大小写。该函数与 POSIX 兼容,可与 strncasecmp 一起在多个操作系统上使用,后者实现了对两个字符串中一定数量的字符进行不区分大小写的比较。后者的参数可以和类型为 size_t 的第三个参数一起传递给函数。

注意,这些函数的返回值可以直接用于条件语句中。

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

int main() {
    const char* str1 = "hello there 2";
    const char* str3 = "Hello there 2";

    !strcasecmp(str1, str3) ?
        printf("strings are equal\n") :
        printf("strings are not equal\n");

    !strncasecmp(str1, str3, 5) ?
        printf("strings are equal\n") :
        printf("strings are not equal\n");

    exit(EXIT_SUCCESS);
}

输出:

strings are equal
strings are equal

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中不区分大小写的字符串比较

发布时间:2023/12/18 浏览次数:225 分类:Python

在 python 中,有三种主要的方法用来进行不区分大小写的字符串比较,它们是 lower()、upper()和 casefold()。本教程将讨论在 Python 中对两个或多个字符串变量进行不区分大小写比较的一些方法。

Bash 中的字符串比较运算符

发布时间:2023/05/18 浏览次数:213 分类:操作系统

在本文中,我们将使用 if 语句解释 Bash 中的字符串比较。运行在 Linux 中,提供命令行界面供用户执行不同命令的 shell 程序称为 Bash shell。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便