-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem11.c
More file actions
98 lines (87 loc) · 2.03 KB
/
problem11.c
File metadata and controls
98 lines (87 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isValidString(char *str)
{
int len = strlen(str);
if (len < 1 || len > 50)
{
printf("!! Invalid Input !!\n");
return 1;
}
while (*str)
{
if (!((*str >= 'a' && *str <= 'z') || (*str >= 'A' && *str <= 'Z')))
{
printf("!! Invalid Input !!\n");
return 1;
}
str++;
}
return 0;
}
char *readString()
{
char *str = NULL;
int size = 0;
int capacity = 7;
char ch;
str = (char *)malloc(capacity * sizeof(char));
if (str == NULL)
{
printf("!! Memory Allocation Failed !!\n");
return NULL;
}
while (1)
{
size = 0;
while ((ch = getchar()) != '\n' && (ch != EOF))
{
if (size >= capacity - 1)
{
capacity *= 2;
char *temp = realloc(str, capacity * sizeof(char));
if (temp == NULL)
{
free(str);
printf("!! Memory Allocation Failed !!\n");
return NULL;
}
str = temp;
}
str[size++] = ch;
}
str[size] = '\0';
if (!isValidString(str))
break;
printf("!! Try Again with valid Input: ");
}
return str;
}
int countJewels(char *jewels, char *stones)
{
int jewelLen = strlen(jewels);
int stoneLen = strlen(stones);
int jewelCount = 0;
for (int i = 0; i < stoneLen; i++)
{
for (int j = 0; j < jewelLen; j++)
{
if (stones[i] == jewels[j])
jewelCount++;
}
}
return jewelCount;
}
int main()
{
printf("Enter the stones that are jewels: ");
char *jewels = readString();
printf("Enter the type of stones: ");
char *stones = readString();
int jewelsNo = countJewels(jewels, stones);
printf("The no of stones that are jewels: %d", jewelsNo);
free(jewels);
free(stones);
return 0;
}