自定义函数实现两个字符串的长度比较功能。
时间: 2023-06-04 07:06:16 浏览: 72
可以使用 strlen 函数来得到两个字符串的长度,然后进行比较。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
int compare(char *str1, char *str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len1 > len2) {
return 1;
} else if (len1 < len2) {
return -1;
} else {
return 0;
}
}
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = compare(str1, str2);
if (result == 1) {
printf("'%s' is longer than '%s'\n", str1, str2);
} else if (result == -1) {
printf("'%s' is shorter than '%s'\n", str1, str2);
} else {
printf("'%s' and '%s' have the same length\n", str1, str2);
}
return 0;
}
```
运行结果:
```
'hello' is shorter than 'world'
```
相关推荐
![](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)