c语言==判断字符串是否相等
时间: 2024-05-24 13:12:17 浏览: 11
可以使用strcmp函数来判断两个字符串是否相等。
strcmp函数的原型为:
int strcmp(const char *str1, const char *str2);
该函数返回值为0表示两个字符串相等,返回值小于0表示str1小于str2,返回值大于0表示str1大于str2。
示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
char str3[] = "hello";
if(strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal\n");
} else {
printf("str1 and str2 are not equal\n");
}
if(strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal\n");
} else {
printf("str1 and str3 are not equal\n");
}
return 0;
}
输出结果:
str1 and str2 are not equal
str1 and str3 are equal
相关问题
c语言如何判断字符串是否相等
在C语言中,判断字符串是否相等可以使用预定义函数strcmp()。该函数需要两个字符串作为参数,返回值是整型,如果两个字符串相等,返回值为0,否则返回其他整数值。下面是一个例子代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "Hello";
if (strcmp(str1, str2) == 0)
printf("两个字符串相等\n");
else
printf("两个字符串不相等\n");
return 0;
}
```
输出:
```
两个字符串相等
```
c语言如何判断两个字符串是否相等
在C语言中,可以使用strcmp()函数来判断两个字符串是否相等。
strcmp()函数的用法如下:
int strcmp(const char *str1, const char *str2);
其中,str1和str2是要比较的两个字符串。
如果str1和str2相等,函数返回0;如果str1小于str2,则返回一个负数;如果str1大于str2,则返回一个正数。
例如:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "hello";
char str2[] = "world";
char str3[] = "hello";
if (strcmp(str1, str2) == 0)
{
printf("str1 and str2 are equal\n");
}
else
{
printf("str1 and str2 are not equal\n");
}
if (strcmp(str1, str3) == 0)
{
printf("str1 and str3 are equal\n");
}
else
{
printf("str1 and str3 are not equal\n");
}
return 0;
}
```
输出结果为:
```
str1 and str2 are not equal
str1 and str3 are equal
```
可以看出,strcmp()函数能够准确地判断两个字符串是否相等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)