C-library style strings implement the cstring replace Function

Source: Internet
Author: User

// No1 solution: strtok and strcat <br/> char * strreplaceno1 (char * STR, char * oldpart, char * newpart) <br/>{< br/> char temp [256], refer [256]; </P> <p> memset (temp, 0, sizeof (temp )); <br/> strcpy (refer, STR); </P> <p> If (! Memcmp (STR, oldpart, strlen (oldpart) <br/> strcat (temp, newpart); <br/> char * PCH; <br/> PCH = strtok (refer, oldpart); <br/> while (PCH! = NULL) <br/>{< br/> strcat (temp, PCH); <br/> strcat (temp, newpart); <br/> PCH = strtok (null, oldpart); <br/>}< br/> PCH = STR; <br/> If (! Memcmp (STR + strlen (refer)-strlen (oldpart), oldpart, strlen (oldpart) <br/> temp [strlen (temp)-strlen (newpart)] = '/0'; <br/> strcpy (STR, temp); <br/> return STR; <br/>}

 

// NO2 solution: strstr and strcat <br/> char * strreplaceno2 (char * STR, const char * oldpart, const char * newpart) <br/>{< br/> char temp [256]; <br/> memset (temp, 0,256); <br/> const int size = strlen (oldpart ); <br/> const int sizenew = strlen (newpart); <br/> int off = 0; <br/> char * PCH = strstr (STR, oldpart ); <br/> int pos1 = 0, pos2 = 0; <br/> while (PCH! = NULL) <br/>{< br/> pos2 = PCH-STR; <br/> memmove (temp + off, STR + pos1, pos2-pos1 ); <br/> strcat (temp, newpart); <br/> off ++ = pos2-pos1 + sizenew; <br/> pos1 = pos2 + size; <br/> PCH = strstr (PCH + size, oldpart); <br/>}< br/> PCH = STR; <br/> strcat (temp, STR + pos1); <br/> strcpy (STR, temp); <br/> return STR; <br/>}

 

Test is not attachedProgramAfter careful testing, there should be no problem.

 

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.