The String.replace
method replaces all the characters or substrings with the replacement character or string, and returns the replaced string as a new string.
stringObj.replace(char oldChar, char newChar)
stringObj.replace(CharSequence oldText, CharSequence newText)
where:
This returns a string with the old characters replaced.
class Main {public static void main( String args[] ) {String str = "hat";String newStr = str.replace('h', 'c');System.out.println(newStr);}}
In the code above, we have created a hat
string and called the replace method on the hat
string. We then call replace('h', 'c')
; this will replace all the character h
in the string with the character c
. This returns the replaced cat
string.
class Main {public static void main( String args[] ) {String str = "babby babby";String newStr = str.replace("bb", "dd");System.out.println(newStr);}}
In the code above, we have created an str
string with the value babby babby
. We then call the replace
method as replace("bb", "dd")
. This replaces all of the bb
substring with dd
string and returns a new baddy baddy
string.