Search for a character from a string and return the pointer to the first match,
The first write may be like this:
Char * strchr (const char * STR, char c) {<br/> assert (STR! = NULL); <br/> while (* STR & * STR ++! = C); <br/> If (* Str) <br/> return (char *) STR; <br/> else <br/> return NULL; <br/>}
In view of some strcpy writing experience, this code is not a big problem, but there are still several small problems, mainly due to incomplete consideration:
- Because the ++ operation is not correctly processed, this function cannot return the correct result. For example, if you search for the character 'E' from "hello", the returned string should be "ello ", however, according to the above Code, we are judging! STR ++! After = C, STR executes the ++ operation, pointing to the next position of the character, so it needs to be slightly modified.
- What if the character to be searched for is a null Terminator '/0'?
Therefore, after modification:
Char * strchr (const char * STR, char c) {<br/> assert (STR! = NULL); <br/> while (* STR & * Str! = C) STR ++; <br/> If (* STR | * STR = C) <br/> return (char *) STR; <br/> else <br/> return NULL; <br/>}
Similarly, the strrchr function of another version is:
Char * strrchr (const char * STR, char c) {<br/> assert (STR! = NULL); <br/> const char * TMP = NULL; <br/> while (* Str) {<br/> If (* STR = C) <br/> TMP = STR; <br/> STR ++; <br/>}< br/> If (* STR = C) <br/> return (char *) STR; <br/> else <br/> return (char *) TMP; <br/>}