指针实现strcmp c例子
时间: 2023-02-16 21:50:31 浏览: 71
好的,这是一个用指针实现 `strcmp` 函数的例子:
```
#include <stdio.h>
#include <string.h>
int my_strcmp(const char *s1, const char *s2)
{
while (*s1 && *s2 && *s1 == *s2) {
s1++;
s2++;
}
return *s1 - *s2;
}
int main()
{
char str1[] = "abcdefg";
char str2[] = "abcdefh";
int result = my_strcmp(str1, str2);
if (result > 0) {
printf("str1 > str2\n");
} else if (result == 0) {
printf("str1 = str2\n");
} else {
printf("str1 < str2\n");
}
return 0;
}
```
其中,`my_strcmp` 函数中,每次用指针 `s1` 和 `s2` 分别指向两个字符串的当前字符,如果两个字符相同,就继续比较下一个字符。如果两个字符不同或者其中一个字符串已经到了末尾,就停止比较并返回当前字符的 ASCII 码之差。
相关问题
c语言模拟系统函数strcmp
C语言中的strcmp函数用于比较两个字符串是否相等,如果相等则返回0,如果不相等则返回非0值。下面是模拟实现strcmp函数的代码:
```c
#include <stdio.h>
#include <assert.h>
int my_strcmp(const char* str1, const char* str2) {
assert(str1 && str2); // 断言指针不为空
while (*str1 == *str2) { // 比较两个字符串的每个字符
if (*str1 == '\0') { // 如果两个字符串都比较完了
return 0; // 返回0表示相等
}
str1++; // 指针后移
str2++;
}
return(*str1 - *str2); // 返回不相等字符的差值
}
```
上面的代码中,我们首先使用assert函数判断指针是否为空,然后使用while循环比较两个字符串的每个字符,如果两个字符串都比较完了,则返回0表示相等,否则返回不相等字符的差值。
下面是一个使用my_strcmp函数的例子:
```c
#include <stdio.h>
int main() {
char* p = "abcq";
char* q = "abbb";
int ret = my_strcmp(p, q);
if (ret > 0) {
printf(">\n"); // p指向的字符串大于q指向的字符串
} else if (0 == ret) {
printf("=\n");
} else {
printf("<\n");
}
return 0;
}
```
运行结果为:
```
>
```
c语言strcmp函数用法
strcmp函数是C语言中的字符串比较函数,用于比较两个字符串是否相等。其函数原型为:
```
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2分别是指向要比较的两个字符串的指针。
函数返回值为整数类型,具体含义如下:
- 若s1等于s2,返回0;
- 若s1小于s2,返回负数;
- 若s1大于s2,返回正数。
比较规则是按照字典序逐个字符比较,直到出现不同的字符或者某个字符串结束为止。
例如,下面是一个使用strcmp函数的例子:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 equals 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](https://img-home.csdnimg.cn/images/20210720083646.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)