August 1999
CA208 : 'C' PROGRAMMING

QUESTION 3

Total Marks: 20 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to
Question 3

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) {
   int count=0;
   while (*str != '\0') {
       str++;
       count++;
     }
    return count;
}

 

(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) {
   char *current = str;

   while(*current!=aChar && *current!= ' \0' ) {
        current++;
   }

   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) {
   char *rchar=' \0' ;

    while(*str!=' \0' ) {
        if(*str==aChar) rchar = str;
        str++;
    }
  return rchar;

}

 

(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)  {
   while(*str!= ' \0 ' )  {
     if(strlchr(set, *str) == ' \0 ' )
        return 1;
      str++;
   }
return0;
}