All for Joomla All for Webmasters

Java String replace

The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.

Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char values.


Signature

There are two type of replace methods in java string.

  1. public String replace(char oldChar, char newChar)
  2. and
  3. public String replace(CharSequence target, CharSequence replacement)

The second replace method is added since JDK 1.5.


Parameters

oldChar : old character

newChar : new character

target : target sequence of characters

replacement : replacement sequence of characters


Returns

replaced string


Java String replace(char old, char new) method example

  1. public class ReplaceExample1{
  2. public static void main(String args[]){
  3. String s1=“makeforsure is a very good website”;
  4. String replaceString=s1.replace(‘a’,‘e’);//replaces all occurrences of ‘a’ to ‘e’
  5. System.out.println(replaceString);
  6. }}

Output :

jevetpoint is e very good website

Java String replace(CharSequence target, CharSequence replacement) method example

  1. public class ReplaceExample2{
  2. public static void main(String args[]){
  3. String s1=“my name is khan my name is java”;
  4. String replaceString=s1.replace(“is”,“was”);//replaces all occurrences of “is” to “was”
  5. System.out.println(replaceString);
  6. }}

Output :

my name was khan my name was java
PinIt
submit to reddit

Leave a Reply

Top