Saturday 11 August 2012

Java String Replace Example


This Java String Replace example describes how replace method of Java String class can be used to replace character or substring by new one.



String replace(char oldChar,char newChar)



Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceFirst(String regex,String replacement)



Replaces the first substring of this string that matches the given regular expression with the given replacement.


String replaceAll(String regex, String replacement)



Replaces each substring of this string that matches the given regular expression with the given replacement.

See the example given below:


public class JavaStringReplaceExample {

 public static void main(String args[]) {

  String str = "Replace Region";

  /**
   * Replaces all occurrences of given character with
   * new one and returns new String object.
   **/
  System.out.println(str.replace('R', 'A'));

  /**
   * Replaces only first occurrences of given String
   * with new one and returns new String object.
   **/
  System.out.println(str.replaceFirst("Re", "Ra"));

  /**
   * Replaces all occurrences of given String with new
   * one and returns new String object.
   **/
  System.out.println(str.replaceAll("Re", "Ra"));

 }

}


The output is:


Aeplace Aegion
Raplace Region
Raplace Ragion

No comments:

Post a Comment