gpt4 book ai didi

c - K&R 2.5 解决方案修改为字符串之间匹配的输出位置/值

转载 作者:行者123 更新时间:2023-11-30 16:52:24 24 4
gpt4 key购买 nike

K&R 2.5 要求:编写函数 any(s1,s2),该函数返回字符串 s1 中出现字符串 s2 中的任何字符的第一个位置,如果 s1 不包含 s2 中的字符,则返回 -1。 (标准库函数 strpbrk 执行相同的工作,但返回指向该位置的指针。)

使用此处给出的第一个解决方案 ( http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_2:Exercise_5 ),我想修改测试值以输出匹配的位置。

也就是说,如果一切正常,测试值只会给出“通过”。如果没有匹配项,我修改了第 127 行以输出“不匹配”(并且这个非常简单的 mod 有效),但是修改第 142 行以显示匹配的位置/值不起作用。如果我只使用“leftstr[left]”作为值,我会得到奇怪的值(L、'等),如果我尝试使用“(leftstr[left]-'0')”进行纠正,我也会感到奇怪值(韩文字符、L、? 等)

理想情况下,我想知道如何提示匹配的位置和值(eS)。仅供引用,我只在 K&R c 左右。 2.9 和自学,因此您越多地使用该(早期)点的 Material ,或者对此之外的任何内容的基本解释,我就越感谢您的回答。

我复制了测试驱动程序,其中包含下面标记的修改行。提前致谢。

/* test driver */

...

    for (left = 0; left < numlefts; left++)
{
for (right = 0; right < numrights; right++)
{
pos = any(leftstr[left], rightstr[right]);
ptr = strpbrk(leftstr[left], rightstr[right]);

if (-1 == pos)
{
if (ptr != NULL)
{
printf("Test %d/%d failed.\n", left, right);
++failed;
}
else
{
printf("Test %d/%d passed, without match. \n", left, right); //mod
++passed;
}
}
else
{
if (ptr == NULL)
{
printf("Test %d/%d failed.\n", left, right);
++failed;
}
else
{
if (ptr - leftstr[left] == pos)
{
printf("Test %d/%d passed, match at %c \n", left, right,
leftstr[left]); //mod w/ issue
++passed;
}
else
{
printf("Test %d/%d failed.\n", left, right);
++failed;
}
}
}
}
}
printf("\n\nTotal passes %d, fails %d, total tests %d\n", passed, failed,
passed + failed);
return 0;
}

最佳答案

If I just use "leftstr[left]" as the value, I get weird values

当然,当您尝试打印 char * 时,您可能会得到奇怪的值(leftstr[left] 是整个字符串 s1) 与转换说明符 c

modifying line 142 to display the location/value of the match is not working.

                        printf("Test %d/%d passed, match at %c \n", left, right,
leftstr[left]); //mod w/ issue

这正在工作:

            printf("Test %d/%d passed, match at position %d, value %c\n"
, left, right, pos, *ptr); //mod w/o issue

关于c - K&R 2.5 解决方案修改为字符串之间匹配的输出位置/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243299/

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