我用 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()
。
最佳答案
简而言之:
所以,如果你有这些字符串:
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/