August
1999 QUESTION 3 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
In C, there is no
special type to represent a string. Instead, a string is simply an array of the standard
type char, and it is the responsibility of the programmer to ensure that they allocate,
manipulate and delete these arrays correctly.
|
||
(a) | Give a simple declaration for a string which consists of maximum of 10 letters. | [1] |
char mystring[10];
|
||
(b) | Implement the library function int strlen(const char* str) which returns the number of characters in the string str. |
[4] |
A sample definition of
strlen follows: int
strlen(const char* str) {
|
||
(c) | Implement the library function char* strlchr(const char* str, char aChar) which returns a pointer to the first (leftmost) occurrence of the character aChar in the string str. If no such character is found, the function should return NULL. |
[5] |
A sample definition of
strlchr follows: char*
strlchr(const char* str, char aChar) { while(*current!=aChar
&& *current!= ' \0' ) { return current;
|
||
(d) | Without reversing the string, implement the
library function char* strrchr(const char* str, char aChar) which returns a pointer to the last (rightmost) occurrence of the character aChar in the string str. If no such character is found, the function should return NULL. |
[5] |
A sample definition as
follows: char*
strrchr(const char* str, char aChar) { while(*str!='
\0' ) { }
|
||
(e) | Using your definition of strlchr, implement
the function int strmember(const char* str, const char* set) where the function will which returns 1 if the string str consists solely of characters that are contained in set. The order in which the characters appear can differ, therefore there is no implication of equality. |
[5] |
A sample definition as follows: int
strmember(const char* str, const char* set) {
|