[Database function source code analysis series] (6) strchr

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.