c语言判断两个字符串是否相同
时间: 2023-12-02 19:06:15 浏览: 60
在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相同
```
相关问题
c语言判断两个字符串是否相等
在C语言中,我们可以通过strcmp函数来判断两个字符串是否相等。strcmp函数的原型为:
int strcmp(const char *str2, const char *str1);
其中,str1和str2是两个要比较的字符串。如果str1和str2相等,strcmp函数返回0;如果str1大于str2,strcmp函数返回正数;如果str1小于str2,strcmp函数返回负数。
举例来说,比较两个字符串"Hello"和"Hello"的代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
if(strcmp(str1, str2) == 0) {
printf("字符串相等!\n");
}
else {
printf("字符串不相等!\n");
}
return 0;
}
```
上述代码中,我们先定义两个字符串变量str1和str2,并赋值为"Hello"。然后使用strcmp函数比较str1和str2的值是否相等,如果相等,则输出"字符串相等!",否则输出"字符串不相等!"。
需要注意的是,strcmp函数比较的是字符串中的内容,即字符集合,而不是字符串的地址。因此,只要两个字符串的内容相同,它们就被认为是相等的。
写一个C语言函数判断两个字符串是否相同
可以使用strcmp函数来判断两个字符串是否相同,该函数的原型为:
int strcmp(const char *s1, const char *s2);
其中,s1和s2分别为要比较的两个字符串,如果它们相同,函数返回0,否则返回非0值。下面是一个示例代码:
#include <stdio.h>
#include <string.h>
int isSameString(const char *s1, const char *s2)
{
return strcmp(s1, s2) == 0;
}
int main()
{
char str1[] = "hello";
char str2[] = "world";
char str3[] = "hello";
printf("%d\n", isSameString(str1, str2)); // 输出0,表示不相同
printf("%d\n", isSameString(str1, str3)); // 输出1,表示相同
return 0;
}
相关推荐
![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_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)