模拟实现strcmp函数

strcmp

int strcmp ( const char * str1, const char * str2 );

Compare two strings

Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.

 

Parameters

str1

C string to be compared.

str2

C string to be compared.

 

Return Value

Returns an integral value indicating the relationship between the strings:

return valueindicates
<0the first character that does not match has a lower value in ptr1 than in ptr2
0the contents of both strings are equal
>0the first character that does not match has a greater value in ptr1 than in ptr2

 通过查看文档,我们已经大致了解了strcmp函数的用途。它是一个字符串比较函数,用于比较两个字符串是否相等。比较规则是:两个指针分别指向两个字符串的首部,然后开始根据ascii码进行比较,如果相等,则指针移动,接着比较下一个字符;直到连个字符不相等或者是其中一个已经到了\0,则比较结束。

代码:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int Strcmp(const char*str1, const char*str2)
{
	assert(str1);
	assert(str2);
	int ret=0;
	//注意这里的条件不能只是*str1==*str2,因为如果两个指针都走到了‘\0’,则还是满足循环条件,指针又进行了移动,导致后面结果出错
	//而这时其实两个字符串比较结果已经出来,是相等的。所以一定还要要添加条件“其中一个指针已经到达\0"
	while (*str1 == *str2&&*str1!='\0')
	{
		str1++;
		str2++;
	}
	if (*str1 > *str2)
	{
		ret = 1;
	}
	else if (*str1 < *str2)
	{
		ret = -1;
	}
	return ret;
}

int main()
{
	char*str1 = "adc";
	char*str2 = "ad";
	int ret = Strcmp(str1, str2);
	printf("%d", ret);
	system("pause");
	return 0;
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值