用一个函数实现两个字符串的比较
时间: 2024-05-02 20:22:20 浏览: 4
可以使用 strcmp() 函数来比较两个字符串。该函数在 C 语言中非常常用,输入两个字符串,返回值为整型。如果两个字符串相同,返回值为 0。例如:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "hello";
char str2[50] = "world";
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.\n");
}
else {
printf("The first string is greater than the second.\n");
}
return 0;
}
```
输出结果:
```
The first string is less than the second.
```
相关问题
用一个函数实现两个字符串比较
可以使用strcmp函数来实现两个字符串的比较。该函数会比较两个字符串的每一个字符,直到遇到字符串结束符'\0'或者两个字符不相等为止。
函数原型如下:
```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";
char str3[] = "hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("result1: %d\n", result1); //-15
printf("result2: %d\n", result2); //0
return 0;
}
```
在上面的示例中,我们使用strcmp函数比较了str1和str2、str1和str3两个字符串,结果分别为-15和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;
}
```
输出结果为:
```
第一个字符串小于第二个字符串
```