Follow on Facebook

Like and Share on Facebook

Sunday, January 25, 2015

Java String replace


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.

public String replace(char oldChar, char newChar)  
and  
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

public class ReplaceExample1{  
public static void main(String args[]){  
String s1="javatpoint is a very good website";  
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'  
System.out.println(replaceString);  
}}  

Expected Output
jevetpoint is e very good website

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

public class ReplaceExample2{  
public static void main(String args[]){  
String s1="my name is khan my name is java";  
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"  
System.out.println(replaceString);  
}}  
Expected Output:
my name was khan my name was java

No comments:

Post a Comment