Friday 3 March 2017

Java String Replace Method




The replace() method

This method replaces all occurrences of the specified character in the invoking String with another character. The general form is:

String replace(char original, char replacement);

Where original specifies the character to be replaced with the character specified by replacement.
Consider the following example:

ReplaceTest.java

 class ReplaceTest
 {
  public static void main(String arg[])
  {
   String str="Today";

   System.out.println("Before replace():"+str);
   System.out.println("After replace():"+str.replace('T','2'));
  }
 }

The output generated by above program is:
 Before replace():Today
 After replace():2oday

The repaceAll() Method

This method supports regular expression. With regex capability you can perform sophisticated Search on String and then replace characters. This String replace method replaces each matched substring with the replacement String provided.

Syntax of Method:

String replace(String regex, String replacement);

Consider the following example:

ReplaceAllTest.java

class ReplaceAllTest
{
public static void main(String arg[])
{
String str="Ram end Sham";

System.out.println("Before replace():"+str);
System.out.println("After replace():"+str.replaceAll("end", "and"));
}
}

The output generated by above program is:
Before replace():Ram end Sham
After replace() :Ram and Sham



 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats