c - C中的memcmp、strcmp和strncmp有什么区别?

标签 c string c-strings

我用 C 编写了这段小代码来测试 C 中的 memcmp() strncmp() strcmp() 函数。

这是我写的代码:

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

int main() {
        char *word1="apple",*word2="atoms";

        if (strncmp(word1,word2,5)==0)
                printf("strncmp result.\n");
        if (memcmp(word1,word2,5)==0)
                printf("memcmp result.\n");
        if (strcmp(word1,word2)==0)
                printf("strcmp result.\n");
}

因为我对这三个函数感到困惑,有人能解释一下它们之间的区别吗?

我的主要问题是我有一个文件,我在其中标记了它的行,问题是当我标记文件中的单词“atoms”时,我必须停止标记化过程。

我首先尝试了 strcmp() 但不幸的是,当它到达文件中放置单词“atoms”的位置时它并没有停止并继续,但是当我使用memcmp()strncmp() 它停止了,我很高兴。

但后来我想,如果有一个字符串的前 5 个字母是 a、t、o、m、s,并且后面跟着其他字母,那会怎么样。

不幸的是,我的想法是正确的,因为我使用上面的代码测试了它,将 word1 初始化为“atomsaaaaa”,将 word2 初始化为 atoms 和 memcmp()strncmp() 在 if 语句中返回 0。另一方面 strcmp() 它没有。看来我必须使用strcmp()

最佳答案

简而言之:

  • strcmp比较以 null 结尾的 C 字符串
  • strncmp比较最多 N 个以 null 结尾的 C 字符串的字符
  • memcmp比较 N 字节的二进制字节缓冲区

所以,如果你有这些字符串:

const char s1[] = "atoms\0\0\0\0";  // extra null bytes at end
const char s2[] = "atoms\0abc";     // embedded null byte
const char s3[] = "atomsaaa";

那么这些结果成立:

strcmp(s1, s2) == 0      // strcmp stops at null terminator
strcmp(s1, s3) != 0      // Strings are different
strncmp(s1, s3, 5) == 0  // First 5 characters of strings are the same
memcmp(s1, s3, 5) == 0   // First 5 bytes are the same
strncmp(s1, s2, 8) == 0  // Strings are the same up through the null terminator
memcmp(s1, s2, 8) != 0   // First 8 bytes are different

关于c - C中的memcmp、strcmp和strncmp有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095513/

相关文章:

c - 为什么段错误: 11 occurred for my C code?

c - 当我们在 c 中用字符串文字初始化 char 数组时,会发生垃圾收集吗?

c - 为什么 C 中没有 "memsize"返回使用 malloc 在堆中分配的内存块的大小?

java - 在java中使用indexOf分割字符串时遇到问题

字符串追加不起作用;不断覆盖以前的字符串

java - Java 中 Int 的回文检查效率

c - 如何使用 strcmp 对 2d char 数组的行(字符串)进行排序?

用于验证最大 ssh session 数的 C 代码

c - 打印下划线字符来代替整数 0

c++ - 将 UINT32 值转换为 UINT8 数组[4]