Design and test a function that searches the string specified by the first funct
ID: 3621394 • Letter: D
Question
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.
Note that if the function does not find the character, it should return a NULL pointer, not a pointer to a NULL character.
Explanation / Answer
Here is a sample script: ----SAMPLE SCRIPT---- % gcc search.c % a.exe Testing string: one Testing string: two Testing string: three Testing string: Testing string: x Testing string: ZZZz Testing string: X Success -----CODE FOR search.c----- #include /* This function takes a string as its first argument and a char as its second. If the first argument is NULL then NULL is returned. Otherwise if the second argument occurs in the first argument, a pointer to the first occurrence is returned, otherwise NULL is returned. The terminating 0 is considered part of the string when doing this comparison. */ char * search (char * string, char sought) { /*Check if string is NULL and if so do not do search.*/ if (string==NULL)return NULL; /*Keep incrementing the string pointer until we hit a 0 character*/ while(*string) if (*string==sought)return string; else ++string; /*Now string points to the terminating NULL, and we have check if this is the char sought*/ if (*string==sought) return string; /*We didn't find the char*/ return NULL; } /*Test the function search() This function just loops through an array of strings and each char from 0 to 126, and compares the results against strchr() . It prints a message if it finds a mismatch. */ int main(int argc, char**argv) { char*strings[]={"one","two","three","","x","ZZZz"," X"}; int numberstrings=7; int error=0; int i=0; char * string; char c; //the character to test against for (i=0;iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.