strncmp实现方式之一

本文详细解读了C++中自定义的字符串比较函数ho_strncmp的实现方式及使用方法,通过对比其与标准库函数strncmp的异同,展示了在特定场景下如何高效地进行字符串比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

strncmp

int ho_strncmp(const char *s1, const char *s2, size_t n) {
    char *s = (char *)s1;

    int c;
    while (n-- && !(c = *s - *s2) && *s) 
        s++, s2++;

    return c;
}

int main() {

    printf("%d\n", ho_strncmp("https", "http", 5));
    printf("%d\n", strncmp("https", "http", 5));

    printf("%d\n", ho_strncmp("http", "https", 5));
    printf("%d\n", strncmp("http", "https", 5));

    printf("%d\n", ho_strncmp("http", "https", 4));
    printf("%d\n", strncmp("http", "https", 4));
    return 0;
}


转载于:https://my.oschina.net/guonaihong/blog/402118

### C语言 `strncmp` 函数使用说明 #### 定义与功能 `strncmp` 是 C 语言标准库中的一个函数,用于比较两个字符串的前 n 个字符。如果这两个字符串在这 n 个字符内相同,则返回0;如果不相同则返回非零值表示差异。 #### 声明形式 该函数声明于 `<string.h>` 头文件中,其原型如下所示[^2]: ```c int strncmp(const char *str1, const char *str2, size_t n); ``` 参数解释: - `const char *str1`: 要比较的第一个字符串指针。 - `const char *str2`: 要比较的第二个字符串指针。 - `size_t n`: 需要比较的最大字符数。 返回值含义: 当第一个不同之处位于左串小于右串时返回负数; 完全匹配或指定长度范围内都一致的情况下返回0; 反之亦然,在遇到不相同的字符处左边大于右边会得到正整数值。 #### 实现示例 下面给出一段简单的自定义实现代码作为参考: ```c #include <stdio.h> // 自定义的 strncmp 函数 int My_strncmp(const char* str1, const char* str2, int num) { for (int i = 0; i < num && (str1[i] != '\0' || str2[i] != '\0'); ++i) { if (str1[i] != str2[i]) { return (unsigned char)(str1[i]) - (unsigned char)(str2[i]); } } return 0; } int main() { const char* string1 = "hello"; const char* string2 = "helium"; printf("%d\n", My_strncmp(string1, string2, 3)); // 输出 0 表示前三字符相等 printf("%d\n", My_strncmp(string1, string2, 5)); // 输出负数因为 'o'< 'u' return 0; } ``` 此程序展示了如何创建自己的版本来进行有限范围内的字符串对比操作,并通过具体例子验证了预期行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值