strcmp函数比较字符串
时间: 2023-11-20 13:51:10 浏览: 73
strcmp函数是C语言中用于比较两个字符串的函数。它按照字典序进行比较,即逐个字符比较。具体的比较过程如下:若两个字符相等,则继续比较下一个字符。若两个字符不相等,则返回它们的ASCII码差值(ASCII码值大的字符串大)。如果两个字符串相等,则返回0;如果第一个字符串大于第二个字符串,则返回一个正数;如果第一个字符串小于第二个字符串,则返回一个负数。在使用strcmp函数时,需要包含头文件<string.h>。下面是一个简单的例子:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int ret = strcmp(str1, str2);
if (ret == 0)
printf("str1和str2相等\n");
else if (ret > 0)
printf("str1大于str2\n");
else
printf("str1小于str2\n");
return 0;
}
```
输出结果为"str1小于str2",因为'h'的ASCII码值比'w'的小。
相关问题
C语言用strcmp函数比较字符串与字符0代码
strcmp函数用于比较两个字符串是否相等。如果要比较字符串和字符0的话,可以将字符0转换成字符串,然后再用strcmp函数进行比较。
下面是一个示例代码,可以比较一个字符串和字符0的大小:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "hello";
char str2[] = "0";
int result = strcmp(str1, str2);
if (result == 0)
{
printf("The strings are equal\n");
}
else if (result < 0)
{
printf("The string '0' is greater than 'hello'\n");
}
else if (result > 0)
{
printf("The string 'hello' is greater than '0'\n");
}
return 0;
}
```
在上面的代码中,我们将字符0转换成了一个字符串,然后用strcmp函数比较了字符串"hello"和字符串"0"的大小关系。注意,strcmp函数返回的结果是一个整数,如果两个字符串相等,结果为0,如果第一个字符串小于第二个字符串,结果为负数,如果第一个字符串大于第二个字符串,结果为正数。我们可以根据这个结果判断字符串的大小关系。
调用strcmp函数比较字符串大小时输出结果
当调用 `strcmp()` 函数比较两个字符串大小时,函数会返回一个整数值,表示比较结果。如果字符串相等,则返回值为 0;如果第一个字符串比第二个字符串小,则返回值小于 0;如果第一个字符串比第二个字符串大,则返回值大于 0。
下面是一个比较字符串大小的例子:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 and str2 are equal");
} else if (result < 0) {
printf("str1 is less than str2");
} else {
printf("str1 is greater than str2");
}
return 0;
}
```
在这个例子中,我们先定义了两个字符串 `str1` 和 `str2`,然后调用 `strcmp()` 函数比较它们的大小,将比较结果存储在 `result` 变量中。最后根据 `result` 的值输出相应的结果。如果你运行这段代码,将会输出 "str1 is less than str2",因为在字典序中 "Hello" 比 "World" 要小。