gpt4 book ai didi

C 创建函数计算前两个不匹配字符之间的值差

转载 作者:行者123 更新时间:2023-11-30 14:59:53 30 4
gpt4 key购买 nike

这是一个比较两个字符串以检查它们是否相等的函数,一切正常,直到它们不相等为止。我想计算前两个不匹配字符之间的值差。函数返回一个奇怪的数字。这个想法是创建一个指针来保存不匹配字符的第一个外观和另一个在下一次迭代中执行相同操作的指针,然后返回它们的减法。根据我在这个网站上找到的内容和谷歌研究,到目前为止我已经能够构建这个。

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


int str_eq(const char *s1,const char *s2)
{
int i = 0;
int d = 0;
char *c ,*cp;
while(*s1 != 0 && *s1 != 0)
{
if(*s1 != *s2)
{
*c = s1[i];
*cp = s2[i + d];
d++;
return ((int)(*cp) - (*c));
}
s1++;
s2++;
i++;
}
return (0);

}


main()
{
const char *s1 = "awerrf";
const char *s2 = "awedre";

if(!(str_eq(s1 , s2)))
{
printf("strings are equal");

}
else
{
printf("strings aren't equal %d" ,str_eq(s1 , s2));

}


}

@edit 我已经对函数代码进行了小幅更新,因此 c 指向发现第一个不匹配字符的数组索引,但现在我如何创建另一个与下一个不匹配字符相同的字符性格。

int str_eq(const char *s1,const char *s2)
{
int i = 0;

char *c ,*cp;
while(*s1 != 0 && *s2 != 0)
{
if(*s1 != *s2)
{
c = &s1[i];
return (*c);

}

s1++;
s2++;
i++;
}
return (0);

}

预期结果(测试用例)

    const char *s1 = "dogydf";
const char *s2 = "dosydg";


s1[0] = s2[0]
s1[1] = s2[1]
s1[2] != s2[2] pointer c = &s1[2];
s1[3] = s2[3]
s1[4] = s2[4]
s1[5] != s2[5] pointer cp = %s1[5] , break loop;

return (*cp) - (*c) //(5 - 2)

@edit_2 解决方案 (c) RoadRunner。

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

#define SIZE 2

int str_eq(char *s1, char *s2) {
int indexes[SIZE];
int count = 0, i = 0, j = 0;

while (s1[i] != '\0' && s2[j] != '\0' && count < 2) {
if (s1[i] != s2[j]) {
indexes[count++] = i;
}
i++;
j++;
}

return indexes[1] - indexes[0];
}

int main(void) {
char *s1 = "doedz";
char *s2 = "dogdyy";

printf("Differences = %d\n", str_eq(s1, s2));

return 0;
}

最佳答案

int str_eq(const char *s1,const char *s2){
do{
if(*s1 != *s2){
return ((int)(*s1) - (*s2));
}
}while(*s1++ != 0 && *s2++ != 0);
return (0);
}

关于C 创建函数计算前两个不匹配字符之间的值差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42453637/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com