How to use the java replace character replacement function

Source: Internet
Author: User

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

Related Article

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.