Java String replace() Method

This Java method returns a new string resulting from replacing every occurrence of characters with a new characters

Syntax:
public Str replace(char oldC, char newC)
Parameters:

oldCh - old character.

newCh - new character.

target : target sequence of characters

replacement : replacement sequence of characters

Internal implementation
public String replace(char oldChar, char newChar) { if (oldChar != newChar) { int len = value.length; int i = -1; char[] val = value; while (++i < len) { if (val[i] == oldChar) { break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; } while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c; i++; } return new String(buf, true); } } return this; }


This fucntion returns a string by replacing oldCh with newCh.

public class Test { public static void main(String args[]) { String S1 = new String("the quick fox jumped"); System.out.println("Original String is ': " + S1); System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox", "dog")); System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a')); } }


Output:
Original String is ': the quick fox jumped String after replacing 'fox' with 'dog': the quick dog jumped String after replacing all 't' with 'a': ahe quick fox jumped
Java String replace(char old, char new) method example
public class Test { public static void main(String args[]) { String str1="cprogramcoding is a very good website"; String re=str1.replace('o','a'); System.out.println(re); } }


Output:
cpragramcading is a very gaad website
Java String replace(CharSequence target, CharSequence replacement) method example
public class Test { public static void main(String args[]) { String str1="My name is java"; String re=str1.replace("is","was"); System.out.println(re); } }


Output:
My name was java
Java String replace() Method Example
public class Test { public static void main(String[] args) { String str1 = "oooooo-hhhh-oooooo"; String str2= str1.replace("h","s"); System.out.println(str2); str2 = str2.replace("s","h"); System.out.println(str2); } }


Output:
oooooo-ssss-oooooo oooooo-hhhh-oooooo



Instagram