Strchr:
// Strchr # include <stdio. h> char * strchr (const char * s, int c) {for (; * s! = (Char) C; ++ s) {If (* s = '\ 0') {return NULL ;}} return (char *) s ;} int main (INT argc, char ** argv) {char string [] = "The quick brown dog jumps over the lazy Fox "; char fmt1 [] = "1 2 3 4 5"; char fmt2 [] = "12345678901234567890123456789012345678901234567890"; char * pdest = NULL; int result; char ch; printf ("string to be searched: \ n \ t % s \ n", string ); printf ("\ t % s \ n", fmt1, fmt2); CH = 'R'; P Rintf ("Search CHAR: \ t % C \ n", CH); pdest = strchr (string, CH); Result = pdest-string + 1; if (pdest! = NULL) printf ("Result: \ tfirst % C found at position % d \ n", CH, result); elseprintf ("result: \ t % C not found \ n "); CH = '\ 0'; // test the special character printf (" Search CHAR: \ t % C (here \ '\ 0 \', cannot be displayed) \ n ", CH); pdest = strchr (string, CH ); result = pdest-string + 1; if (pdest! = NULL) printf ("Result: \ tfirst % C found at position % d \ n", CH, result); elseprintf ("result: \ t % C not found \ n "); Return 0 ;}
1. When the passed pointer is null, It is not checked in the function.
2. When the search character is '\ 0', it should always be found! The return value is the '\ 0' address at the end of the string. But think about the usage of returning this pointer? It makes no practical sense. This also makes strchr functions easy to write errors, such:
char *Strchr(const char *s, int c){while (*s != '\0' && *s != (char)c)s++;if (*s == '\0')return NULL;return (char *)s;}
The above program is wrong, because when the query is '\ 0', it is considered to have reached the end of the string, I didn't expect '\ 0' to make the two while conditions false at the same time! Pay attention to this error. Therefore, we should change it:
char *Strchr(const char *s, int c){while (*s != '\0' && *s != (char)c)s++;if (*s == (char)c)return (char *)s;return NULL;}
You must first test whether C is found.