c语言strcmp函数用法
时间: 2023-08-24 11:13:05 浏览: 49
strcmp函数是C语言中的字符串比较函数,用于比较两个字符串的大小。
函数原型:
```
int strcmp(const char *s1, const char *s2);
```
参数说明:
- s1:被比较的第一个字符串。
- s2:被比较的第二个字符串。
返回值:
- 当 s1 等于 s2 时,返回 0。
- 当 s1 大于 s2 时,返回一个大于 0 的值。
- 当 s1 小于 s2 时,返回一个小于 0 的值。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if(result == 0)
printf("str1和str2相等\n");
else if(result > 0)
printf("str1大于str2\n");
else
printf("str1小于str2\n");
return 0;
}
```
输出结果为:
```
str1小于str2
```
相关问题
c语言函数strcmp的用法
函数原型:
```c
int strcmp(const char *str1, const char *str2);
```
函数说明:
`strcmp` 函数用于比较两个字符串是否相同,它的返回值有以下三种情况:
- 当 `str1` 和 `str2` 相等时,返回值为0。
- 当 `str1` 大于 `str2` 时,返回值大于0。
- 当 `str1` 小于 `str2` 时,返回值小于0。
函数参数:
- `str1`:用于比较的第一个字符串。
- `str2`:用于比较的第二个字符串。
函数示例:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "Hello";
int result1, result2, result3;
result1 = strcmp(str1, str2);
result2 = strcmp(str2, str1);
result3 = strcmp(str1, str3);
printf("strcmp(str1, str2) = %d\n", result1);
printf("strcmp(str2, str1) = %d\n", result2);
printf("strcmp(str1, str3) = %d\n", result3);
return 0;
}
```
输出结果为:
```
strcmp(str1, str2) = -15
strcmp(str2, str1) = 15
strcmp(str1, str3) = 0
```
可以看出,`strcmp` 函数返回的结果符合预期。
C语言 strcmp用法
C语言中的strcmp函数用于比较两个字符串的大小。它的函数原型如下所示:
```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>
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 equal to str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
```
运行上述代码,输出结果为"str1 is less than str2",因为字符串"hello"在字典序中小于字符串"world"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)