用一个函数实现两个字符串比较
时间: 2024-03-17 20:45:28 浏览: 24
可以使用strcmp函数来实现两个字符串的比较。该函数在C语言中是标准库函数,可以直接调用。函数原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2分别是需要比较的两个字符串,函数会返回一个整数值,表示两个字符串的大小关系。如果s1大于s2,则返回一个正整数;如果s1小于s2,则返回一个负整数;如果s1等于s2,则返回0。
以下是一个使用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 greater than str2.\n");
}
else if(result < 0)
{
printf("str1 is less than str2.\n");
}
else
{
printf("str1 is equal to str2.\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2.
```
相关问题
用一个函数实现两个字符串的比较
可以使用字符串库中的strcmp函数来实现两个字符串的比较。
函数原型为:
```c
int strcmp(const char *s1, const char *s2);
```
函数说明:
strcmp函数比较s1和s2两个字符串,如果s1和s2相等,返回0;如果s1大于s2,返回一个正整数;如果s1小于s2,返回一个负整数。
示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("两个字符串相等\n");
} else if (result > 0) {
printf("str1大于str2\n");
} else {
printf("str1小于str2\n");
}
return 0;
}
```
一个函数实现两个字符串的比较
可以使用字符串库中的strcmp函数来比较两个字符串。该函数会返回一个整数值,如果两个字符串相等则返回0,如果第一个字符串小于第二个字符串则返回一个负数,如果第一个字符串大于第二个字符串则返回一个正数。
示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if(result == 0) {
printf("两个字符串相等\n");
} else if(result < 0) {
printf("第一个字符串小于第二个字符串\n");
} else {
printf("第一个字符串大于第二个字符串\n");
}
return 0;
}
```
输出结果为:
```
第一个字符串小于第二个字符串
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)