K&R 2.5 asks: Write the function any(s1,s2), which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location.)
Using the first solution given here (http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_2:Exercise_5), I'd like to modify the test values to output the location of the match(es).
That is, the test value just gives "passed" if everything works all right. I modified line 127 to output "without match" if there was not a match (and this very simple mod works), but modifying line 142 to display the location/value of the match is not working. If I just use "leftstr[left]" as the value, I get weird values (L, ', etc.) and if I try to correct using say "(leftstr[left]-'0')" I also get weird values (Korean character, L, ?, etc.)
Ideally I would like to know how to cue up both the position and the value of the match(eS). FYI I am only at about K&R c. 2.9 and self-studying so the more you can use material from that (early) point forward, or a basic explanation of anything beyond that, the more I would appreciate your answers.
I copied the test driver with the modded lines tagged below. Thanks in advance.
/* 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;
}
Of course you may get weird values when you try to print a
char *
(whichleftstr[left]
is, the whole string s1) with the conversion specifierc
.This is working: