c语言比较两个字符串是否相同
时间: 2023-07-26 08:34:55 浏览: 51
在C语言中,可以使用strcmp函数来比较两个字符串是否相同。该函数的原型如下:
```c
int strcmp(const char *str1, const char *str2);
```
该函数会比较str1和str2两个字符串的字典序,如果两个字符串相同,则返回0;如果str1小于str2,则返回一个负数;反之,如果str1大于str2,则返回一个正数。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello";
char str2[100] = "World";
if (strcmp(str1, str2) == 0) {
printf("两个字符串相同。\n");
} else {
printf("两个字符串不同。\n");
}
return 0;
}
```
该代码会输出"两个字符串不同。",因为str1和str2不相同。
相关问题
C语言比较两个字符串是否相同
在C语言中,我们可以使用strcmp函数来比较两个字符串是否相同。
strcmp函数的原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2分别是要比较的两个字符串。
如果两个字符串相同,strcmp函数返回值为0。如果s1小于s2,返回值小于0。如果s1大于s2,返回值大于0。
下面是一个例子:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "Hello";
char str2[100] = "Hello";
int result = strcmp(str1, str2);
if(result == 0)
printf("两个字符串相同\n");
else
printf("两个字符串不同\n");
return 0;
}
```
这个程序会输出“两个字符串相同”。
c语言判断两个字符串是否相同
在C语言中,可以使用标准库函数strcmp()来判断两个字符串是否相同。
strcmp()函数的原型为:
```c
int strcmp(const char *str1, const char *str2);
```
其中,str1和str2是要比较的两个字符串。
如果两个字符串相同,函数返回0;如果str1大于str2,函数返回一个正整数;如果str1小于str2,函数返回一个负整数。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50] = "hello";
char str2[50] = "world";
char str3[50] = "hello";
if(strcmp(str1, str2) == 0)
printf("str1和str2相同\n");
else
printf("str1和str2不同\n");
if(strcmp(str1, str3) == 0)
printf("str1和str3相同\n");
else
printf("str1和str3不同\n");
return 0;
}
```
输出结果为:
```
str1和str2不同
str1和str3相同
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)