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);
}
相关推荐
还卿一钵无情泪1 小时前
Unsloth 微调 构建自己的大模型 没有GPU也能微调
linux·开发语言·人工智能·python·大模型·nlp·unsloth
高山有多高1 小时前
【Linux笔记】IO模型
linux
Nil2082 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
不会就选b2 小时前
Linux之TCP理论<1>
linux·运维·服务器
小π军3 小时前
操作系统面试题
java·linux·服务器
Lsetea4 小时前
curl用IP测试HTTPS报证书不匹配:--resolve与Host头别混用
linux·https·ssl证书·openssl·curl
Hao2854 小时前
Windows11 下把 WSL2 Ubuntu 26.04 装到 D 盘完整
linux
wanderist.4 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
Android系统攻城狮4 小时前
Linux Gstreamer深度解析之gst_audio_encoder_get_frame_samples_min调用流程与实战(六十)
linux·运维·服务器·音视频·gstreamer音视频·音视频进阶·gstreamer音视频进阶
All for pursuit.4 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode