How to use the java replace character replacement function
Replace (char oldChar, char newChar)
Public class MainClass
{
Public static void main (String args [])
{
String s1 = new String ("hello ");
String s2 = new String ("GOODBYE ");
String s3 = new String ("spaces ");
System. out. printf ("s1 = % sns2 = % sns3 = % snn", s1, s2, s3 );
// Test method replace
System. out. printf ("Replace 'L' with 'l' in s1: % snn", s1.replace ('L', 'L '));
} // End main
}
Result
S1 = hello
S2 = GOODBYE
S3 = spaces
Replace 'L' with 'l' in s1: heLLo
Replace spaces/
Public class MainClass {
Public static void main (String [] arg ){
String text = "To be or not to be, that is the question .";
String newText = text. replace ('', '/'); // Modify the string text
System. out. println (newText );
}
}
Result
To/be/or/not/to/be,/that/is/the/question.
Some friends wrote a replace function.
// Replace string functions
// String strSource-source String
// String strFrom-substring to be replaced
// String strTo-String to be replaced
Public static String replace (String strSource, String strFrom, String strTo)
{
// If the substring to be replaced is null, the source string is directly returned.
If (strFrom = null | strFrom. equals (""))
Return strSource;
String strDest = "";
// Length of the substring to be replaced
Int intFromLen = strFrom. length ();
Int intPos;
// Replace the string cyclically
While (intPos = strSource. indexOf (strFrom ))! =-1)
{
// Obtain the left substring of the matched string
StrDest = strDest + strSource. substring (0, intPos );
// Add the substring after replacement
StrDest = strDest + strTo;
// Modify the source string to the substring after matching the substring
StrSource = strSource. substring (intPos + intFromLen );
}
// Add a child string that does not match
StrDest = strDest + strSource;
// Return
Return strDest;
}