c语言字符串怎么比较大小
时间: 2023-12-09 14:04:10 浏览: 40
C语言中的字符串比较大小可以使用标准库函数`strcmp`。`strcmp`函数会按照字典序逐个比较两个字符串,直到出现不同的字符或者其中一个字符串结束。如果第一个字符串在字典序中排在第二个字符串之前,则返回一个负整数;如果第一个字符串在字典序中排在第二个字符串之后,则返回一个正整数;如果两个字符串相等,则返回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("%s is less than %s\n", str1, str2);
} else if (result > 0) {
printf("%s is greater than %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
return 0;
}
```
输出:
```
hello is less than world
```
相关问题
C语言字符串比较大小
在C语言中,字符串的比较大小可以使用strcmp函数来实现。strcmp函数是C标准库中的一个字符串比较函数,用于比较两个字符串的大小。
strcmp函数的原型如下:
```c
int strcmp(const char *str1, const char *str2);
```
该函数接受两个参数,分别是要比较的两个字符串str1和str2。它会按照字典序逐个比较两个字符串中对应位置的字符,直到遇到不同的字符或者其中一个字符串结束为止。
如果str1小于str2,则返回一个负数;如果str1等于str2,则返回0;如果str1大于str2,则返回一个正数。
下面是一个示例代码,演示了如何使用strcmp函数比较两个字符串的大小:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 小于 str2\n");
} else if (result == 0) {
printf("str1 等于 str2\n");
} else {
printf("str1 大于 str2\n");
}
return 0;
}
```
输出结果为:
```
str1 小于 str2
```
c语言字符串比较大小
在C语言中,可以使用strcmp函数来比较两个字符串的大小。
strcmp函数的用法如下:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2都是要比较的字符串。如果s1小于s2,返回一个负整数;如果s1等于s2,返回0;如果s1大于s2,返回一个正整数。
例如,下面的代码可以比较两个字符串的大小:
```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 less than str2\n");
} else if (result == 0) {
printf("str1 is equal to str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
```
输出结果为:
```
str1 is greater than str2
```