用字符串比较函数比较字符串大小
时间: 2024-03-24 19:37:59 浏览: 15
可以使用标准库中的字符串比较函数strcmp()来比较两个字符串的大小。函数原型如下:
```c
int strcmp(const char *str1, const char *str2);
```
其中,str1和str2分别是要比较的两个字符串。函数返回值为0表示两个字符串相等,返回值大于0表示str1大于str2,返回值小于0表示str1小于str2。
例如,下面的代码比较了两个字符串的大小:
```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
```
相关问题
字符串比较函数mystrcmp
my_strcmp()函数是一个自定义的字符串比较函数,用于比较两个字符串的大小。它的实现方式可以根据具体需求进行编写。下面是一个示例实现:
```c
int my_strcmp(const char *str1, const char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char*)str1 - *(unsigned char*)str2;
}
```
这个函数会逐个比较两个字符串中的字符,直到遇到不相等的字符或者其中一个字符串结束。如果第一个字符串大于第二个字符串,则返回一个大于0的数;如果两个字符串相等,则返回0;如果第一个字符串小于第二个字符串,则返回一个小于0的数。
字符串比较函数strcmp
strcmp函数是C语言中的字符串比较函数,用于比较两个字符串的大小。该函数的原型为int strcmp(const char *str1, const char *str2),其中str1和str2分别为需要比较的两个字符串。函数返回值为0表示两个字符串相等,返回值大于0表示str1大于str2,返回值小于0表示str1小于str2。在使用该函数时,需要注意传入的参数必须为指向字符串的指针,且字符串必须以'\0'结尾。
代码示例:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 equals to str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is less than str2\n");
}
return 0;
}
```