侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

C库函数-strcmp和strncmp

zze
zze
2024-03-25 / 0 评论 / 0 点赞 / 14 阅读 / 6455 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

strcmp

函数原型:

#include <string.h>

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

功能:strcmp 函数用于比较两个字符串 str1str2,根据字典顺序返回一个整数值,用来指示两个字符串的关系。

参数:

  • str1:指向第一个字符串的指针。

  • str2:指向第二个字符串的指针。

返回值:

  • 如果 str1str2 相等,返回 0

  • 如果 str1 小于 str2(按照字典顺序),返回一个负数。

  • 如果 str1 大于 str2(按照字典顺序),返回一个正数。

示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);

    if (result < 0) {
        printf("str1 is less than str2\n");
    } else if (result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 and str2 are equal\n");
    }

    return 0;
}

strncmp

函数原型:

#include <string.h>

int strncmp(const char *str1, const char *str2, size_t n);

功能:strncmp 函数与 strcmp 类似,但仅比较两个字符串的前 n 个字符。如果在前 n 个字符中找到了区分两个字符串的差异,它将停止比较并返回结果。

参数:

  • str1:指向第一个字符串的指针。

  • str2:指向第二个字符串的指针。

  • n:要比较的字符数量。

返回值:

  • 如果前 n 个字符相等,返回 0

  • 如果 str1 的前 n 个字符小于 str2 的前 n 个字符,返回一个负数。

  • 如果 str1 的前 n 个字符大于 str2 的前 n 个字符,返回一个正数。

示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    size_t n = 3; // 只比较前3个字符

    int result = strncmp(str1, str2, n);

    if (result < 0) {
        printf("The first %zu characters of str1 are less than the same number of characters in str2\n", n);
    } else if (result > 0) {
        printf("The first %zu characters of str1 are greater than the same number of characters in str2\n", n);
    } else {
        printf("The first %zu characters of str1 and str2 are equal\n", n);
    }

    return 0;
}

注意事项

  • strcmpstrncmp 都是区分大小写的,所以在比较时会考虑字符的大小写差异。

  • 使用 strncmp 可以防止潜在的缓冲区溢出,特别是在不知道字符串确切长度时。不过,如果 n 设置得过大,超过了较短字符串的实际长度,strncmp 也会一直比较到较短字符串的末尾,然后再判断是否结束。

0

评论区