Exercise 2-5 (any char in a string)

Chapter_2     Exercise_2-4 getbits     Exercise_2-6







Exercise 2-5     K&R, p. 48


Exercise 2-5. 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.)




anychar.c         download


#include <stdio.h> // for printf(), scanf()

#define LENGTH 100 // max word length

int any(char s[], char t[]); // return first location of a char of t[] in string s[] or -1

int main()
{
int pos;
char s1[LENGTH], s2[LENGTH];

printf("Type a word: ");
scanf("%s", s1);
printf("Type another word: ");
scanf("%s", s2);

printf("The first location of any of \"%s\" in \"%s\": ", s2, s1);
pos = any(s1, s2);
printf("%d", pos);
if (pos < 0) {printf(" (not found)\n");}
else {printf(" (%c)\n", s1[pos]);}

return 0;
}

int any(char s[], char t[]) // return first location of a char of t[] in string s[] or -1
{
int i, j;

for (i = 0; t[i] != '\0'; i++)
{
for (j = 0; s[j] != '\0'; j++)
{
if (s[j] == t[i]) {return j;}
}
}

return -1; // not found
}
/*
gcc anychar.c -o anychar
./anychar
Type a word: abracadabra
Type another word: bro
The first location of any of "bro" in "abracadabra": 1 (b)

./anychar
Type a word: abracadabra
Type another word: a
The first location of any of "a" in "abracadabra": 0 (a)

./anychar
Type a word: abracadabra
Type another word: vip
The first location of any of "vip" in "abracadabra": -1 (not found)

./anychar
Type a word: abracadabra
Type another word: hocus
The first location of any of "hocus" in "abracadabra": 4 (c)
*/









Chapter_2     Exercise_2-4 BACK_TO_TOP getbits     Exercise_2-6



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo