c语言字符串比较
时间: 2023-06-21 20:16:16 浏览: 60
在C语言中,字符串可以使用字符串常量或字符数组表示。要比较两个字符串,可以使用库函数strcmp(),其语法如下:
```c
int strcmp(const char *str1, const char *str2);
```
其中,str1和str2分别表示要比较的两个字符串。如果两个字符串相等,则返回值为0;如果str1大于str2,则返回值大于0;如果str1小于str2,则返回值小于0。
示例代码:
```c
#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("str1大于str2\n");
} else {
printf("str1小于str2\n");
}
return 0;
}
```
相关问题
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`。它的原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
该函数接受两个参数,分别是要比较的两个字符串`s1`和`s2`。它会返回一个整数值,表示两个字符串的大小关系。
当`s1`小于`s2`时,返回一个负数;当`s1`等于`s2`时,返回0;当`s1`大于`s2`时,返回一个正数。
例如,下面是使用`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("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 less than str2
```
这表示字符串"Hello"小于字符串"World"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)