Jun 22, 2021

K & R : Exercise 2.5 - alternate strpbrk

K & R : Exercise 2.5 - alternate strpbrk

Problem

Write the function any(s1, s2) which returns the first location in the string s1, where any charecter from s2 occurs or -1 if s1 contains no charecters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location).


Solution

First we will traverse s1 charecter by charecter (outer for loop with index i). Second loop (with index j) will traverse s2. Each charecter in s1 is tested against charecter in s2, if found then break and return index. If not charecter is not found then -1 is returned. Solution would looks something like below.

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

int any(const char *s1, const char *s2);
int main()
{
  char *s1 = "hello";
  char *s2 = "world";
  int idx;

  idx = any(s1, s2);

  printf("First character matching %c is at %d\n", s1[idx], idx);

  return 0;
}
int any(const char *s1, const char *s2)
{
  int i, j;
  int k = 0;
  for(i = 0; i < strlen(s1); i++) {
    for(j = 0; j < strlen(s2); j++) {
      if(s1[i] == s2[j])
         break;
    }
    if(j != strlen(s2)) 
      break;
  }
  if(i == strlen(s1))
     return -1;
  else
     return i;
}
First character matching l is at 2

Links

No comments :

Post a Comment