| « Coming to a grinding halt | Python + web? » |
Fri, Jan 19, 2007
![[Icon]](rsc/img/chain_link.gif)
K&R exercise 2.5 - create a function that finds the first occurence of a character in string 1 that is also present in string 2, and returns either the position (if a match is found) or -1 (if not)
I wrote it, and tested it, but it never returned the -1 result. Because, of course, when using getline() to get the two strings, there's always a carriage return at the end of each string. Took me a few moments to realize this, and then I breathed a sigh of relief that I hadn't made a mistake after all.
The exercise doesn't mention "except for '\n's" so I left it as-is, but I did test that it works properly if you crop out the '\n', just to be sure.
Aside from that slight oddity, it was a remarkably simple exercise, and most of the code was recycled from the previous example. . .
Follow up:
/* K&R exercise 2.5: Write any(s1, s2) that returns the first location in s1
* where any character in s2 occurs, or -1 if no match is found.
* The exercise makes no mention of excluding '\n' so all lines of sub-MAXLINE
* length will return a valid result in this program */
#include <stdio.h>
#define MAXLINE 500
int getline(char line[], int maxline);
signed int any(char s1[], char s2[]);
int main()
{
char string1[MAXLINE];
char string2[MAXLINE];
int i;
printf("Give me a string:\n");
getline(string1, MAXLINE);
printf("Give me the comparison string:\n");
getline(string2, MAXLINE);
i = any(string1, string2);
if (i == -1)
printf("No match found\n");
else
printf("The character at array position %d, \'%c\', is present in both strings\n", i, string1[i]);
return 0;
}
int getline(char line[], int maxline)
{
int i, c;
for (i=c=0; c != '\n' && (c = getchar()) != EOF && i < maxline-1; ++i)
line[i] = c;
line[i] ='\0';
return i;
}
signed int any(char s1[], char s2[])
{
int i, j;
/* Match should default to -1 */
signed int match = -1;
/* Loop through the characters in s1 */
for (i = 0; s1[i] != '\0' && match == -1; ++i)
{
j = 0;
/* Check each character in s1 against all charcters in s2 */
while (s2[j] != '\0' && match == -1)
{
if (s1[i] == s2[j])
/* If a match is found, set match==i */
match = i;
++j;
}
}
return match;
} ![[Links]](http://geekblog.oneandoneis2.org/skins/112/rsc/img/chain_link.gif)
Hmm.. new look for twitter? I hope it gets less "Ick! Change! Put it back!" nonsense than Facebook..
08/02/12
Facebook Syndication Error
09/02/12
![]()
I last listened to:
Johann Pachelbel - Canon in D major
Most recent photo:
Submersible houseboat