Problem
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
- Next Article - K & R : Exercise 2.6 - setbits
- Previous Article - K & R : Exercise 2.4 - squeeze string
- All Article - K & R Answer
No comments :
Post a Comment