C语言第三十八弹--模拟实现strcmp

使用C语言模拟实现strcmp

strcmp 比较两个字符串大小 底层实现:int strcmp(const char* str1,const char* str2)

思路:了解strcmp作用是比较字符串大小,那么就要分三种情况,大,小,相等。然后分别进行处理。比较方法根据实现了解是使用指针进行比较。

代码如下:

c 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int my_strcmp(const char* s1, const char* s2)
{
	assert(s1 && s2);//断言
	while (*s1 == *s2)//字符相同情况
	{
		if (*s1 == '\0')//符合while条件只要其中一个是'\0'证明两个都已经比较完成
		{
			return 0;
		}
		s1++;
		s2++;
	}

	if (*s1 > *s2)//*s1 > *s2
	{
		return 1;
		//return *s1 - *s2;
	}
	else//其它情况
	{
		return -1;
		//return *s1 - *s2;
	}

	//简洁写法 return *s1-*s2 缺点:返回值是随机值
}


int main()
{
	int ret=my_strcmp("abcde", "abcd");
	printf("%d\n",ret);
}
相关推荐
数模竞赛Paid answer7 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆7 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
三言老师8 小时前
秘诀-如何远程SSN访问家里的八台电脑(frp 实操方案)
linux·运维·ssh
想吃火锅10059 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
举手9 小时前
Dispatcher模块剖析
linux·c++
Nil2089 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣10 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
allforgood10 小时前
运行容器
linux
Light_It11 小时前
Linux 内核参数 pci-stub.ids=
linux·kernel
RisunJan12 小时前
Linux命令-scriptreplay(终端会话回放)
linux·运维·chrome