String replacement, php string replacement

Source: Internet
Author: User

String replacement, php string replacement

String replacement

Write a string replacement function, such as the parent string "123123123123". Replace the child string "123" with "12345" or "12 ".

Ideas:

Use the database function strstr () to locate the substring. Use strcpy () for replacement. The location and replacement operations are repeated until the location is NULL.


Sample Code:

# Include <stdio. h> # include <stdlib. h> # include <string. h>/* replace the substring s1 in str with s2 */char * strReplace (char * str, char * s1, char * s2) {// apply for a space char * s = malloc (50) in the heap; // clear memset (s, 0, 50 ); // copy str to strcpy (s, str); char buf [50]; char * pStr = strstr (s, s1); while (pStr) {// save strcpy (buf, pStr + strlen (s1); // s2 replace s1strcpy (pStr, s2 ); // move pStrpStr + = strlen (s2); // Add the post-order content to strcpy (pStr, buf); // find the next position to replace pStr = strstr (pStr, s1);} str = s; return str;} void main () {// "123"-> "12345" char * str = "123123123123 "; printf ("original string \ n"); printf ("% s \ n", str); str = strReplace (str, "123", "12 "); printf ("after replacement \ n"); printf ("% s \ n", str); free (str); system ("pause ");}
Run







In JAVA, how can I replace the string with the replace function and print the output code ??

Public String getStr (String aa, String bb)
{
String str = "abcdefg"
String str1 = str1.replace (aa, bb); // aa is the String to be replaced, and bb is the content to be replaced
Return str;
}

If you have any questions, continue to ask

C language to replace a character in a string

Character replacement is simple, and it is difficult to replace strings.
# Include <stdio. h>
Char * replaceAll (char * src, char oldChar, char newChar ){
Char * head = src;
While (* src! = '\ 0 '){
If (* src = oldChar) * src = newChar;
Src ++;
}
Return head;
}

Main ()
{
Char s [] = "21 ~ 31 ~ 41 ";
Char * p = s;
P = replaceAll (s ,'~ ',',');
Printf ("% s \ n", p );

}

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.