Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_2.5_any.c
1240 views
1
/**
2
* Exercise 2.5
3
*
4
* Write the function any(s1,s2) which returns the first location in the string
5
* s1 where any character from the string s2 occurs, or -1 if s1 contains
6
* no characters from s2. ( The standard library function strpbrk does
7
* the same job but retuns a pointer to the location
8
*
9
**/
10
11
#include<stdio.h>
12
#define MAXLINE 1000
13
14
int mgetline(char line[],int maxline);
15
int any(char s1[],char s2[]);
16
17
int main(void)
18
{
19
char s1[MAXLINE],s2[MAXLINE];
20
int val;
21
22
/* Give the first string s1 */
23
24
mgetline(s1,MAXLINE);
25
26
/* Give the second string s2 */
27
28
mgetline(s2,MAXLINE);
29
30
val = any(s1,s2);
31
32
printf("%d",val);
33
34
return 0;
35
}
36
37
int mgetline(char s[],int lim)
38
{
39
int i,c;
40
for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
41
s[i]=c;
42
43
if(c=='\n')
44
s[i++]=c;
45
s[i]='\0';
46
}
47
48
49
int any(char s1[],char s2[])
50
{
51
int i,j;
52
53
for(i=0;s1[i]!='\0';++i)
54
{
55
// iterate through s2 while trying to find matching character from s1
56
for(j=0;(s1[i]!=s2[j]) && s2[j]!='\0';++j)
57
; // continue
58
59
if(s2[j]!='\0' && s2[j] != '\n') { // check that s2 [j]! = '\n', since s1 and s2 both have the character '\n' in the penultimate position of the string.
60
return i;
61
}
62
}
63
64
return -1;
65
}
66