Java's string and stringbuffer do not provide a substring replacement function. To implement this function, you must write your own function. The following are two implementation methods: method 1, use regular expression replacement (in fact, the regular expression is not actually used. The pattern parameter of the compile function. likes the regular expression string to be treated only as the literal value ).
Import java. util. RegEx .*;
Public class test {
Public static void main (string [] ARGs ){
String S = "My name is Xinyu! ";
Replacefromstring (S, "name", "nickname ");
System. Out. println (s );
}
Public static void replacefromstring (string string1, string string2, string string3 ){
String newstring = pattern. Compile (string2, pattern. Literal). matcher (string1). replaceall (string3 );
System. Out. println (newstring );
}
}
Method 2: Use the indexof string to find the sub-string, add the content before the original string and the replacement string to the stringbuffer, and only find the original string)
/**
* @ Author Hans Bergsten, gefion software (www.gefionsoftware.com)
*/
Public class stringutils {
/*** Returns a string with all occurrences of the string from * Replaced by the string.
** @ Return the new string */
Public static string replaceinstring (string in, string from, string ){
Stringbuffer sb = new stringbuffer (in. Length () * 2 );
String posstring = in. tolowercase ();
String cmpstring = from. tolowercase ();
Int I = 0;
Boolean done = false;
While (I <in. Length ()&&! Done ){
Int start = posstring. indexof (cmpstring, I );
If (START =-1 ){
Done = true;
} Else {
SB. append (in. substring (I, start) + );
I = start + from. Length ();
}
}
If (I <in. Length ()){
SB. append (in. substring (I ));
}
Return sb. tostring ();
}
}