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 );
}