String processing function (2): strchr

Source: Internet
Author: User

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:

  1. 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.
  2. 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/>}

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.