c语言strcmp函数用法
时间: 2023-09-21 20:11:01 浏览: 58
strcmp函数是C语言中的字符串比较函数,用于比较两个字符串是否相等。其函数原型为:
```
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2分别是指向要比较的两个字符串的指针。
函数返回值为整数类型,具体含义如下:
- 若s1等于s2,返回0;
- 若s1小于s2,返回负数;
- 若s1大于s2,返回正数。
比较规则是按照字典序逐个字符比较,直到出现不同的字符或者某个字符串结束为止。
例如,下面是一个使用strcmp函数的例子:
```
#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 less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```
相关问题
c语言函数strcmp的用法
函数原型:
```c
int strcmp(const char *str1, const char *str2);
```
函数说明:
`strcmp` 函数用于比较两个字符串是否相同,它的返回值有以下三种情况:
- 当 `str1` 和 `str2` 相等时,返回值为0。
- 当 `str1` 大于 `str2` 时,返回值大于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, result2, result3;
result1 = strcmp(str1, str2);
result2 = strcmp(str2, str1);
result3 = strcmp(str1, str3);
printf("strcmp(str1, str2) = %d\n", result1);
printf("strcmp(str2, str1) = %d\n", result2);
printf("strcmp(str1, str3) = %d\n", result3);
return 0;
}
```
输出结果为:
```
strcmp(str1, str2) = -15
strcmp(str2, str1) = 15
strcmp(str1, str3) = 0
```
可以看出,`strcmp` 函数返回的结果符合预期。
C语言 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[] = "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"。