写一函数,实现两个字符串的比较。要求不可调用strcmp函数
时间: 2024-05-11 12:16:04 浏览: 19
好的,我会为您编写一段实现两个字符串比较的函数,不调用strcmp函数。以下是代码:
```c
int compareStrings(char *str1, char *str2) {
int i = 0, flag = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
flag = 1;
break;
}
i++;
}
if (flag == 0 && str1[i] == '\0' && str2[i] == '\0')
return 0;
else
return -1;
}
```
该函数采用了逐个比较字符串中每个字符的方法来确定是否相等。如果发现有不同的字符,则将flag标志为1,表示两个字符串不匹配。如果两个字符串都结束了,则视为匹配。如果出现不匹配,则返回-1,否则返回0。
相关问题
用一个函数实现两个字符串比较
可以使用strcmp函数来实现两个字符串的比较。该函数在C语言中是标准库函数,可以直接调用。函数原型如下:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2分别是需要比较的两个字符串,函数会返回一个整数值,表示两个字符串的大小关系。如果s1大于s2,则返回一个正整数;如果s1小于s2,则返回一个负整数;如果s1等于s2,则返回0。
以下是一个使用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 greater than str2.\n");
}
else if(result < 0)
{
printf("str1 is less than str2.\n");
}
else
{
printf("str1 is equal to str2.\n");
}
return 0;
}
```
输出结果为:
```
str1 is less than str2.
```
调用strcmp函数比较字符串大小时输出结果
当调用 `strcmp()` 函数比较两个字符串大小时,函数会返回一个整数值,表示比较结果。如果字符串相等,则返回值为 0;如果第一个字符串比第二个字符串小,则返回值小于 0;如果第一个字符串比第二个字符串大,则返回值大于 0。
下面是一个比较字符串大小的例子:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 and str2 are equal");
} else if (result < 0) {
printf("str1 is less than str2");
} else {
printf("str1 is greater than str2");
}
return 0;
}
```
在这个例子中,我们先定义了两个字符串 `str1` 和 `str2`,然后调用 `strcmp()` 函数比较它们的大小,将比较结果存储在 `result` 变量中。最后根据 `result` 的值输出相应的结果。如果你运行这段代码,将会输出 "str1 is less than str2",因为在字典序中 "Hello" 比 "World" 要小。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)