<分区>
我有两个大字符串,
char str1[] = "letsgosomewhereandfindsomethingnew";
char str2[] = "letsgosomewhereandfindcomethingnew";
我想获取字符串的第一个不匹配字符,前提是字符串的长度相同。
<分区>
我有两个大字符串,
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/