strcmp(s1, s2);的代码演示
时间: 2023-06-25 17:04:04 浏览: 168
假设我们有两个字符串s1和s2,可以使用strcmp函数比较它们的大小。
```c
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "hello";
char s2[20] = "world";
if (strcmp(s1, s2) == 0) {
printf("s1 and s2 are equal\n");
} else if (strcmp(s1, s2) < 0) {
printf("s1 is less than s2\n");
} else {
printf("s1 is greater than s2\n");
}
return 0;
}
```
输出结果:
```
s1 is less than s2
```
在上面的代码中,我们首先定义了两个字符串s1和s2,然后使用strcmp函数进行比较。如果两个字符串相等,strcmp函数返回0;如果s1小于s2,返回值小于0;如果s1大于s2,返回值大于0。根据返回值的不同,我们可以判断两个字符串的大小关系。在这个例子中,s1的字典序小于s2,因此输出"s1 is less than s2"。
相关问题
用c语言编写函数strcomp(s1, s2),实现两个字符串的比较,返回值分别为1、0、-1表示s1>s2, s1=s2, s1<s2 的情况。
好的,以下是一个可能的C语言实现:
```c
#include <stdio.h>
#include <string.h>
int strcomp(char *s1, char *s2) {
int cmp = strcmp(s1, s2);
if (cmp == 0) {
return 0;
} else if (cmp > 0) {
return 1;
} else {
return -1;
}
}
int main() {
char s1[] = "hello";
char s2[] = "world";
int result = strcomp(s1, s2);
printf("%d\n", result); // 输出-1,因为s1 < s2
return 0;
}
```
这个函数使用了C语言标准库中的strcmp函数来比较两个字符串。strcmp函数的返回值为零表示两个字符串相等,大于零表示第一个字符串大于第二个字符串,小于零表示第一个字符串小于第二个字符串。根据返回值,我们可以返回1、0或-1,分别表示s1>s2、s1=s2或s1<s2的情况。在main函数中,我们演示了如何使用这个函数来比较两个字符串。
strcmp
strcmp是C语言中的字符串比较函数,用于比较两个字符串是否相等。它的函数原型为:
```
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2是两个要比较的字符串。如果s1和s2相等,返回值为0;如果s1小于s2,返回值小于0;如果s1大于s2,返回值大于0。
例如,下面的代码演示了如何使用strcmp比较两个字符串:
```
#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);
printf("result2 = %d\n", result2);
return 0;
}
```
上述代码输出结果为:
```
result1 = -15
result2 = 0
```
因为"hello"小于"world",所以result1返回-15;"hello"等于"hello",所以result2返回0。
阅读全文
相关推荐














