c语言比较字符串相等
时间: 2023-11-05 17:04:49 浏览: 144
在 C 语言中,可以使用 `strcmp()` 函数来比较字符串是否相等。该函数在 `<string.h>` 头文件中声明,它会按字典顺序比较两个字符串,并返回一个整数值来表示比较结果。
如果两个字符串相等,`strcmp()` 函数的返回值为 0;如果字符串不相等,则返回一个非零值,其正负性取决于两个字符串的相对顺序。
下面是一个使用 `strcmp()` 函数比较字符串是否相等的简单示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
```
在上述示例中,我们使用 `strcmp()` 函数比较了两个字符串 `str1` 和 `str2` 是否相等。如果相等,则输出 "The strings are equal.",否则输出 "The strings are not equal."。
相关问题
c语言 判断字符串相等
在C语言中,判断两个字符串是否相等可以使用strcmp函数。该函数的原型为int strcmp(const char *s1, const char *s2),其中s1和s2分别为要比较的两个字符串。如果两个字符串相等,则返回0,否则返回非0值。可以使用该函数来实现判断字符串相等的功能。另外,也可以使用循环遍历两个字符串的每个字符进行比较,如果有不同的字符则返回1,否则返回0。
用c语言比较字符串大小
在 C 语言中比较两个字符串的大小可以使用库函数 `strcmp()`。`strcmp()` 函数会比较两个字符串的 ASCII 码值,如果第一个字符串的 ASCII 码值比第二个字符串的小,则返回负数;如果第一个字符串的 ASCII 码值比第二个字符串的大,则返回正数;如果两个字符串相等,则返回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'
```