C语言中strcmp
时间: 2024-04-23 17:18:24 浏览: 22
在C语言中,strcmp是一个用于比较两个字符串的函数。它的原型定义在<string.h>头文件中,函数的声明如下:
int strcmp(const char *str1, const char *str2);
该函数接受两个参数,分别是要比较的两个字符串str1和str2。它会按照字典顺序逐个比较两个字符串中的字符,直到遇到不同的字符或者其中一个字符串结束为止。
如果str1小于str2,则返回一个负数;如果str1大于str2,则返回一个正数;如果str1等于str2,则返回0。
下面是一个使用strcmp函数的示例:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}
return 0;
}
输出结果为:str1 is less than str2
相关问题
c语言中strcmp
`strcmp`是C语言中的一个字符串比较函数,用于比较两个字符串是否相等。其函数原型为:
```c
int strcmp(const char* str1, const char* str2);
```
其中`str1`和`str2`分别为要比较的两个字符串。函数返回值为整型,如果`str1`小于`str2`,则返回一个负整数;如果`str1`等于`str2`,则返回0;如果`str1`大于`str2`,则返回一个正整数。
以下是两个使用`strcmp`函数的例子:
引用:
```c
#include<stdio.h>
#include<string.h>
#include<assert.h>
//模拟实现
int my_strcmp(const char* str1, const char* str2) {
assert(str1 && str2);
while (*str1 == *str2) {
if (*str1 == '\0') {
return 0;
}
str1++;
str2++;
}
return(*str1 - *str2);
}
int main() {
int ret1 = my_strcmp("abcd", "abcde");
if (ret1 < 0) {
printf("<\n");
}
else if (ret1 == 0) {
printf("==\n");
}
else {
printf(">\n");
}
return 0;
}
```
引用:
```c
#include<stdio.h>
#include<string.h>
int main() {
char arr1[20] = "zhangsan";
char arr2[] = "zhangsanfeng";
int ret = strcmp(arr1, arr2);
if (ret < 0) {
printf("<\n");
}
else if (ret == 0) {
printf("==\n");
}
else {
printf(">\n");
}
return 0;
}
```
c语言中strcmp函数
在 C 语言中,strcmp 函数用于比较两个字符串是否相等。它的原型如下:
```
int strcmp(const char *str1, const char *str2);
```
其中,str1 和 str2 是要比较的两个字符串。
如果两个字符串相等,strcmp 返回值为 0。
如果 str1 大于 str2,则返回一个正整数。
如果 str1 小于 str2,则返回一个负整数。
strcmp 函数比较的是字符串的 ASCII 码值,因此在比较之前需要确保字符串已经以 '\0' 结尾。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)