Replace substring or a character of String in Java
replace(char old,char new) and replace(String oldsubstr,String newstr) methods of String class can be used to replace a character or substring of String.
These methods return the final replaced string at the end.
Example 1
class StringTest{
public static void main(String args[]){
String fullstr="Goud";
char oldchar='u';
char newchar='o';
String newstr=fullstr.replace(oldchar,newchar);
System.out.println("Replaced string is "+newstr);
}
}
Output 1
Replaced string is Good
Example 2
class StringTest{
public static void main(String args[]){
String fullstr="Where are you ?";
String oldsubstr="are";
String newsubstr="were";
String newstr=fullstr.replace(oldsubstr,newsubstr);
System.out.println("Replaced string is "+newstr);
}
}
Output 2
Replaced string is Where were you ?