C 语言中比较字符串
本文将介绍关于如何在 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
使用 strcasecmp
和 strncasecmp
函数比较忽略字母大小写的字符串
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
相关文章
在 C# 中忽略大小写来比较两个字符串
发布时间:2024/01/03 浏览次数:109 分类:编程语言
-
有 3 种主要方法可用于不区分大小写地比较 C# 中的 2 个字符串:String.ToUpper(),String.ToLower()和 String.Equals()函数。
Python 中不区分大小写的字符串比较
发布时间:2023/12/18 浏览次数:225 分类:Python
-
在 python 中,有三种主要的方法用来进行不区分大小写的字符串比较,它们是 lower()、upper()和 casefold()。本教程将讨论在 Python 中对两个或多个字符串变量进行不区分大小写比较的一些方法。
Bash 中的字符串比较运算符
发布时间:2023/05/18 浏览次数:213 分类:操作系统
-
在本文中,我们将使用 if 语句解释 Bash 中的字符串比较。运行在 Linux 中,提供命令行界面供用户执行不同命令的 shell 程序称为 Bash shell。
如何在 C++ 中忽略大小写的比较两个字符串
发布时间:2023/04/08 浏览次数:436 分类:C++
-
本文介绍了如何在 C++ 中比较两个字符串而忽略大小写的方法。使用 strcasecmp 函数比较两个忽略大小写的字符串
在 PHP 中使用 == 运算符和 STRCMP 函数进行字符串比较
发布时间:2023/03/14 浏览次数:160 分类:PHP
-
本文展示了 == 运算符和 strcmp 函数如何在 PHP 中比较字符串。
JavaScript 中不区分大小写的字符串比较
发布时间:2023/03/10 浏览次数:256 分类:JavaScript
-
本文介绍了如何在 JavaScript 中执行不区分大小写的字符串之间的比较。
JavaScript 中的通配符字符串比较
发布时间:2023/03/09 浏览次数:291 分类:JavaScript
-
本教程展示了如何使用正则表达式,以及它如何通过通配符字符串比较在 JavaScript 中发挥作用。