-
Notifications
You must be signed in to change notification settings - Fork 124
/
exercise05.c
66 lines (53 loc) · 1.54 KB
/
exercise05.c
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
// C Primer Plus
// Chapter 11 Exercise 5:
// Design and test a function that searches the string specified by the first
// function parameter for the first occurrence of a character specified by the
// second function parameter. Have the function return a pointer to the
// character if successful, and a null if the character is not found in the
// string. (This duplicates the way that the library strchr() function works.)
// Test the function in a complete program that uses a loop to provide input
// values for feeding to the function.
#include <stdio.h>
#define LIMIT 50
char * findchar(char *str, const char ch);
int main(void)
{
char string[LIMIT];
char *chloc;
char ch;
// test findchar()
printf("Enter a string to search: ");
fgets(string, LIMIT, stdin);
while (string[0] != '\n')
{
printf("Enter a character to search for: ");
ch = getchar();
// discard rest of line if any
if (ch != '\n')
while (getchar() != '\n')
continue;
chloc = findchar(string, ch);
if (chloc == NULL)
printf("Character %c not found in %s", ch, string);
else
printf("Character %c found at index %lu in %s", ch, chloc - string, string);
// get new input
printf("Enter a string to search (empty line to quit): ");
fgets(string, LIMIT, stdin);
}
puts("Bye");
return 0;
}
char * findchar(char *str, const char ch)
{
// find and return pointer to first occurence of
// char ch in string str. return NULL if not found
while (*str != '\0')
{
if (*str == ch)
return str;
str++;
}
// if ch is not found, return null
return NULL;
}