用c语言编写比较字符串的函数
时间: 2024-05-13 16:16:28 浏览: 18
可以使用strcmp函数来比较两个字符串。该函数的原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2是要比较的两个字符串。
函数返回值有以下几种情况:
- 如果s1和s2相等,返回0。
- 如果s1小于s2,返回负数。
- 如果s1大于s2,返回正数。
下面是一个比较字符串的示例程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50];
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
int result = strcmp(str1, str2);
if (result == 0)
{
printf("The strings are equal.\n");
}
else if (result < 0)
{
printf("The first string is less than the second string.\n");
}
else
{
printf("The first string is greater than the second string.\n");
}
return 0;
}
```
在这个示例程序中,我们首先使用scanf函数分别读入两个字符串,然后使用strcmp函数比较它们。根据strcmp函数的返回值,我们输出相应的结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)