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);
}
相关推荐
GeW8 小时前
新质生产力路线图Linux、数据库、国产化替代一次讲透
linux
zyl76510 小时前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
aningx10 小时前
cachyos 从 GRUB 切换到 rEFInd
linux
第404号工位12 小时前
40块钱二手瘦客户端,如何跑满家庭物联网中枢?(拒绝Docker爆盘实录)
linux·架构·node.js
骑着蜗牛撵大象32714 小时前
Linux 进程间通信之管道:从 pipe() 的内核语义到 FIFO 落地排错
android·java·linux·系统编程·fifo·管道·进程间通信
爱读书的小胖14 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌14 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
..Dauntless..14 小时前
【Linux】一切皆文件和缓冲区
linux·运维·服务器
QMCY_jason14 小时前
x86 ubuntu2204 无gui 安装 openeuler 2203 aarch64版本
linux·运维·服务器
重生之小比特14 小时前
【Linux系统】12 进程程序替换 自定义Shell 命令行解释器
linux·运维·服务器