Thank you for your question.
If you have any questions about the code, or you would like additional
features, please use the "Request Clarification" button in your
browser to request this _before_ rating the answer.
I have to warn you that the search() function does use some C idioms
that look a little concise and mysterious at first . But one gets used
to them.
The main thing to remember here is that the string argument is a
pointer, and incrementing the pointer in the search() function does
NOT change the value of the pointer in the calling function.
I am enclosing the code for the C function you requested below. You
can also find this function at:
http://www.rbnn.com/google/search.c
since sometimes code excerpts do not render well when cut-and-pasted.
When writing test code, a natural question is: how do we know the test
code works? Fortunately, my original version of this program had a bug
(much to my chagrin) and the test code did indeed print out a number
of nasty error messages.
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 <stdlib.h>
/* 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;i<numberstrings;i++){
string=strings[i];
printf("Testing string: %s\n",string);
for (c=0;c<127;++c)
if (search(string,c)!=strchr(string,c)){
error=1;
printf("Failure at %c for string: %s\n",c,string);
}
}
if (error)
printf("Failure\n");
else
printf("Success\n");
}
-----SEARCH STRATEGY----
I used the site:
"Notes on C" at http://www.phys.ufl.edu/~rlliu/comp/cnotes.html to
check some C syntax.
I used search keywords "C specification stdlib" to check the semantics
of strchr . |