c - C中是否有一个库函数返回两个字符串的第一个不匹配字符的位置?

标签 c c-strings

<分区>

我有两个大字符串,

char str1[] = "letsgosomewhereandfindsomethingnew";
char str2[] = "letsgosomewhereandfindcomethingnew";

我想获取字符串的第一个不匹配字符,前提是字符串的长度相同。

最佳答案

大多数库 cstring 比较都设置为排序。您正在寻找不同之处。

所以最好K&R风格,自己动手:

char *p1 = str1;
char *p2 = str2;

while (*p1 && *p2 && (*p1 == *p2))
{
    ++p1;
    ++p2;
}
// p1 and p2 should point to the two different characters (strings match if *p1 == *p2)

未经测试的动态编码

或根据评论进行优化

char *p1 = str1;
char *p2 = str2;

while (*p1 && (*p1 == *p2))
{
    ++p1;
    ++p2;
}
// p1 and p2 should point to the two different characters (strings match if *p1 == *p2)

因为另一个评论现在要求偏移量

int offset;

for (offset = 0; str1[offset] && (str1[offset] == str2[offset]); ++offset)
{
    // Empty block because I hate for statements without bodies
}
// Now you have the number of matching characters in offset

关于c - C中是否有一个库函数返回两个字符串的第一个不匹配字符的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37617920/

相关文章:

c - Libgcrypt 中的 AES CCM 加密和解密

c - 如何将 strcpy() 与数组元素一起使用?

c - 表达式必须有类类型错误

c - 为什么 OpenSSL EVP C 库和 Python 生成的密文不同?

c - 如何从 C 程序为接口(interface)设置 ipv6 地址

c - 声明的含义

指针加法的 C 行为

c++ - MFC CString 构造函数操作

arrays - 是否必须为字符数组的初始化提供 '\0'?