是否有一个标准的 C 函数可以比较两个 C 字符串,并返回指向第一个不同字符的指针,如果字符串相等则返回 NULL?
#include <stdio.h>
int main()
{
const char *p, *s1 = "foobar", *s2 = "foobaz";
p = strdiffchr(s1, s2);
if (!p)
puts("the strings are equal");
else
printf("s1 has %c, where s2 has %c\n", *p, s2[p - s1]);
return 0;
}
编辑:我选择了以下解决方案:
char *strdiffchr(const char *s1, const char *s2)
{
while (*s1 && *s1 == *s2) {
s1++;
s2++;
}
return (*s1 == *s2) ? NULL : (char *)s1;
}
最佳答案
我不认为有这样的功能。不过,可以在单个 for
循环中对其进行编码:
const char *p1, *p2, *s1 = "foobar", *s2 = "foobaz";
for (p1 = s1, p2 = s2 ; *p1 && *p1 == *p2 ; p1++, p2++)
; // Loop body is empty, because everything is done in the header.
const char *p = *p1 || *p2 ? p1 : NULL;
关于c - 获取指向两个 C 字符串之间不同的第一个字符的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21862467/