C-language string replace Function

Source: Internet
Author: User

Ansi c does not provide the string replace function. Some functions are implemented on the Internet, but most of them have a problem: not all replace.

 

For example, this is a test to test string replacing.

If you want to replace test with example, the result of all replace is: this is a example to example string replacing.

Many implementations on the Internet only need to find a result and return it.

 

Here I have written a function for all replicas:

 

Char * strrepl (const char * SRC, char * DST, size_t dst_size, const char * search, const char * replace_with) {<br/> char * replace_buf = (char *) malloc (dst_size); <br/> If (replace_buf) {<br/> replace_buf [0] = 0; <br/> char * P = (char *) SRC; <br/> char * Pos = NULL; <br/> while (Pos = strstr (p, search ))! = NULL) {<br/> size_t n = (size_t) (POS-P); <br/> strncat (replace_buf, P, N> dst_size? <Br/> strncat (replace_buf, replace_with, dst_size-strlen (replace_buf)-1); <br/> P = POS + strlen (Search ); <br/>}< br/> snprintf (DST, dst_size, "% S % s", replace_buf, P); <br/> free (replace_buf ); <br/>}< br/> return DST; <br/>}< 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.