c语言 比较两个字符串
时间: 2023-06-22 13:37:48 浏览: 55
在C语言中,比较两个字符串可以使用strcmp函数。strcmp函数会比较两个字符串的内容,如果相同则返回0,如果不同则返回一个非0的值,这个值表示两个字符串不同的位置的ASCII码差值。
例如,比较字符串str1和字符串str2的代码如下:
```c
if(strcmp(str1, str2) == 0) {
printf("两个字符串相同\n");
} else {
printf("两个字符串不同\n");
}
```
需要注意的是,strcmp函数比较的是字符串的内容,而不是字符串的地址。如果要比较字符串的地址,可以使用==运算符。
相关问题
c语言比较两个字符串
在C语言中,比较两个字符串可以使用标准库函数strcmp。
strcmp函数的原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
该函数接受两个参数,分别是要比较的两个字符串s1和s2。函数返回一个整数值,如果s1等于s2,返回0;如果s1小于s2,返回一个负数;如果s1大于s2,返回一个正数。
以下是一个示例程序,演示了如何使用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("str1 is equal to str2\n");
}
else if (result < 0)
{
printf("str1 is less than str2\n");
}
else
{
printf("str1 is greater than str2\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than 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;
}
```
这个程序会输出“两个字符串相同”。