c语言 编写函数,比较两个字符串是否相等(用指针完成)
时间: 2023-11-29 16:06:16 浏览: 174
可以使用以下代码来比较两个字符串是否相等:
```c
#include <stdio.h>
int compareStrings(char* str1, char* str2) {
while (*str1 == *str2) {
if (*str1 == '\0' || *str2 == '\0')
break;
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0')
return 1; // strings are equal
else
return 0; // strings are not equal
}
int main() {
char str1[100], str2[100];
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
if (compareStrings(str1, str2))
printf("The strings are equal\n");
else
printf("The strings are not equal\n");
return 0;
}
```
在上面的代码中,我们定义了一个名为 `compareStrings` 的函数来比较两个字符串是否相等。该函数接受两个参数,这两个参数都是指向字符数组的指针。在函数中,我们使用一个 while 循环来比较两个字符串中的每个字符。如果两个字符不相等,则返回 0,表示两个字符串不相等。如果两个字符串中的所有字符都相等,则返回 1,表示两个字符串相等。
在主函数中,我们使用 `scanf` 函数从用户那里获取两个字符串。然后,我们调用 `compareStrings` 函数来比较这两个字符串。如果这两个字符串相等,我们将输出 “The strings are equal”,否则我们将输出 “The strings are not equal”。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)