C Pointer operation--replace a character or substring in a string

Source: Internet
Author: User
#include <string.h>
#include <stdio.h>

#include <stdlib.h>

Replaces all S1 characters in the source string with the character S2 void Replace_char (char *result, Char *source, char S1, char S2)
{
int i = 0;
char *q = NULL;

Q = source;
for (i=0; I<strlen (q); i++)
{
if (q[i] = = S1)
{
Q[i] = s2;
}
}
strcpy (result, q);
}


void Replace_string (char *result, Char *source, char* S1, Char *s2)
{
Char *q=null;
Char *p=null;

P=source;
while ((Q=strstr (P, S1))!=null)
{
strncpy (result, p, q-p);
result[q-p]= '//very '; important, must attention!
strcat (result, S2);
strcat (Result, Q+strlen (S1));
strcpy (P,result);
}
strcpy (result, p);
}

void Main ()
{
Char url[64] = "Ad12 fdf5 d12f dfd12 DFP";
Char result[64] = {0};

Replace_char (result, url, ', ' _ ');//Replace All ' characters in URL with ' _ ' characters, resulting in
printf ("Char final result=%s\n", result);
memset (result, 0, sizeof (result));
Replace_string (result, URL, "12", "@@@");//Replace All "12" strings in the URL with a "@@@" string
printf ("String final result=%s\n", result);

}

The results of running separately are as follows:

Test Result: Char final RESULT=AD12_FDF5_D12F_DFD12_DFP

Test results: string:final result=ad@@@ fdf5 d@@@f dfd@@@ DFP


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.