C标准库--strcmp、strncmp函数

本文详细介绍了C标准库中的strcmp和strncmp函数,包括它们的原型、功能、返回值及实现原理。strcmp用于比较两个字符串是否相等,而strncmp则允许指定比较的字符数,提供了一种安全的字符串比较方式。这两个函数在确定字符串匹配和建立字典顺序方面非常实用,但其返回结果可能因实现而异,因此在需要跨平台兼容性时,可能需要自定义比较函数。
摘要由CSDN通过智能技术生成

1、The strcmp function

1.1、Synopsis

#include <string.h>
int strcmp(const char *s1, const char *s2);

1.2、Description

  The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

1.3、Returns

  The strcmp function returns integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or les than the string pointed to by s2.

1.4、Implementing

/* strcmp function */
#include <string.h>

int (strcmp)(const char *s1, const char *s2)
{				/* compare unsigned char s1[], s2[] */
	for (; *s1 == *s2; ++s1, ++s2)
		if (*s1 == '\0')
			return 0;
	return ((* unsigned char *)s1 < * (unsigned char *)s2) ? -1 : +1);
}

1.5、Using

  This function offers the quickest way to determine whether two null-terminateed strings match character for character. You can also use it to establish a lexical ordering between two strings, but that ordering can change among inolementations. If a portable result is important, you must write your own comparsion function, See strcoll and strxfrm.

2、The strcmp function

2.1、Synopsis

#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);

2.2、Description

  The strncmp function compares not more than n characters (characters that follow a null characters are not compared) from the array pointed to by s1 to the array pointed to by s2.

2.3、Returns

2.4、Implementing

/* strncmp function */
#include <string.h>

int (strncmp)(const char *s1, const char *s2, size_t n)
{				/* compare unsigned char s1[max n], s2[max n] */
	for (; 0 < n; ++s1, ++s2, --n)
		if (*s1 != *s2)
			return ((* (unsigned char *)s1 < *(unsigned char *) s2) ? -1 : =1);
		else if (*s1 == '\0')
			return (0);

	return (0);
}

2.5、Using

  The function offers the quickest way to determine whether two character sequences of the same known length match character for character up to and including any null character in both. You can also use it to establish a lexical ordering between two such character swquences, but that ordering can change among implementations. If a portable resulet is important, you must write your own comparison fcunction.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值