C语言中的strcmp()函数是什么?
C库函数 **int strcmp(const char *str1, const char *str2)** 将由 **str1** 指向的字符串与由 **str2** 指向的字符串进行比较。
字符数组称为字符串。
声明
以下是数组的声明:
char stringname [size];
例如:char string[50]; 长度为50个字符的字符串
初始化
- 使用单字符常量:
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量:
char string[10] = "Hello":;
**访问**:使用控制字符串“%s”访问字符串,直到遇到‘\0’。
strcmp()函数
此函数比较两个字符串。
它返回两个字符串中前两个不匹配字符的ASCII码差值。
字符串比较
语法如下:
int strcmp (string1, string2);
如果差值为零 ------ string1 = string2
如果差值为正 ------ string1 > string2
如果差值为负 ------ string1 < string2


示例程序
以下程序演示了strcmp()函数的用法:
#include<stdio.h>
main ( ){
char a[50], b [50];
int d;
printf ("enter 2 strings:
");
scanf ("%s %s", a,b);
d = strcmp (a,b);
if (d==0)
printf("%s is equal to %s", a,b);
else if (d>0)
printf("%s is greater than %s",a,b);
else if (d<0)
printf("%s is less than %s", a,b);
}输出
执行上述程序后,会产生以下结果:
enter 2 strings: bhanu priya bhanu is less than priya
让我们看另一个关于strcmp()的例子。
以下是使用strcmp库函数比较两个字符串的C程序:
示例
#include<stdio.h>
#include<string.h>
void main(){
//Declaring two strings//
char string1[25],string2[25];
int value;
//Reading string 1 and String 2//
printf("Enter String 1: ");
gets(string1);
printf("Enter String 2: ");
gets(string2);
//Comparing using library function//
value = strcmp(string1,string2);
//If conditions//
if(value==0){
printf("%s is same as %s",string1,string2);
}
else if(value>0){
printf("%s is greater than %s",string1,string2);
}
else{
printf("%s is less than %s",string1,string2);
}
}输出
执行上述程序后,会产生以下结果:
Enter String 1: Tutorials Enter String 2: Point Tutorials is greater than Point
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP