Java String API replace() Method Example

1. Java String replace() Overview


In tutorial, We'll learn about Java String replace() method and explanation with examples. replace() method is used to replace a character with another character in a String and this method returns a new string after replacing characters.

In previous tutorial, We've seen How to use Java 11 String API repeat() method.

Java String API replace() Method Example

1.1 Syntax


public String replace​(char oldChar, char newChar)
public String replace​(CharSequence target, CharSequence replacement)

replace() method is available in two variants. First variant takes two char's as input and replace a char by a new char. Where as in second variant, It takes two CharSequence as arguments and replace one CharSequence by new CharSequence.

Here, CharSequence means String, StringBuffer, StringBuilder. Any one of these can be passed as arguments to the second variant of replace().


1.2 Parameters


replace​(char oldChar, char newChar)

oldChar - the old character.
newChar - the new character.

replace​(CharSequence target, CharSequence replacement)

target - The sequence of char values to be replaced
replacement - The replacement sequence of char values

1.3 Returns


String


A string derived from this string by replacing every occurrence of oldChar with newChar.
   
Note: If the oldChar is not present the string then it will return the current string reference. That means original string is unchanged and returns the same obj.

2. String replace() Method Example


We will see now example program on replace method how to replace a character in a String. First will see replacing char by new char. Next, Will see replacing of portion of string with another string.

2.1 public String replace​(char oldChar, char newChar) example


Example program to replace oldChar by newChar.

In this case, we are replacing char '3' with '2'.

String str1 = "w3schools";
String replacedStr1 = str1.replace('3', '2');
System.out.println("Replaced String : "+replacedStr1);

Output:

See the output. Char '3' is replaced with char '2' and returned a new String value "w2schools".

Replaced String : w2schools

2.2 replace​(CharSequence target, CharSequence replacement) example

 

We will replace a string by string in the below program.

String str2 = "Java-W3schools";
String replacedStr2 = str2.replace("oo", "i");
System.out.println("Replaced String : "+replacedStr2);

Here replacing a substring "oo" with string "i".

Output:

Replaced String : Java-W3schils

3. Multiple oldChar occurrences


In the above section, We've every replacement if oldChar appears once in input string. How replace() method behaves if oldChar or target string appear multiple times.

Let us take a look those now.

3.1 replace​(oldChar, newChar) example


See string str3 in the below example where char 'o' appears 4 times. Now, invoking replace method on that str3. See the output.

String str3 = "Welcome to Java-W3scools blog";
String replacedStr3 = str3.replace('o', 'e');
System.out.println("Multiple occurrences replacement done : "+replacedStr3);

Output:

Wow! All occurrences of char 'o' is replaced by char 'e'.

Multiple occurrences replacement done : Welceme te Java-W3sceels bleg

3.2 replace​(target, replacement) example


Here, String "Java" appears twice.

String str4 = "Welcome to Java-W3scools blog for Java developers";
String replacedStr4 = str4.replace("Java", "OOPS");
System.out.println("Multiple occurrences replacement done : "+replacedStr4);

Output:

Wow! 2 occurrences of string "Java" is replaced by "OOPS".


Multiple occurrences replacement done : Welcome to OOPS-W3scools blog for OOPS developers

Note: replace method finds the all occurrences and replaces all of them by given new char or String. If you want to replace only first occurrence then use replaceFirst() method.

Article on How to remove a character from String.

4. replace() Method Internal Code


Below is the it's internal code from String API.

4.1 First Variant



public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
: StringUTF16.replace(value, oldChar, newChar);
if (ret != null) {
return ret;
}
}
return this;
}

Step 1: First checks if oldChar and newChar is same then return current string.

Step 2: Next, checks for the char given in the string. If finds replaces with newChar.

Step 3: Travese through all characters of string. Checks all occurrences then replace with newChar.

4.2 Second Varient


public String replace(CharSequence target, CharSequence replacement) {
String tgtStr = target.toString();
String replStr = replacement.toString();
int j = indexOf(tgtStr);
if (j < 0) {
return this;
}
int tgtLen = tgtStr.length();
int tgtLen1 = Math.max(tgtLen, 1);
int thisLen = length();

int newLenHint = thisLen - tgtLen + replStr.length();
if (newLenHint < 0) {
throw new OutOfMemoryError();
}
StringBuilder sb = new StringBuilder(newLenHint);
int i = 0;
do {
sb.append(this, i, j).append(replStr);
i = j + tgtLen;
} while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
return sb.append(this, i, thisLen).toString();
}

Step 1: First converts both arguments given into String. Because, this method takes String, StringBuffer and StringBuilder.

Step 2: Check the target string is presnt in the current using indexOf() method. This indexOf method returns index of the target string if it finds. Index is stored in variable int j.

Step 3: If returned index is negetive then returns current string. That means, target string is not found in the current string.

Step 4: It will caluelate the expected output string length after all replacement. If it is negetive then will throw OutOfMemoryError.

Step 5: Creates a StringBuffer objct with the length of output string.

Step 6: it will append the substring from index 0 to j (j is from step 2) into stringBuilder.

Step 7: It will perform again indexOf method on string from index j. If it finds then stores the new index in variable j. Otherwords old j value is replaced by new value.

Step 8: If valid index is returned (positive value), next it addes the replacement string into stringBuilder.

Step 9: Repeats the indexOf step till it finds a match. Other wise returns the string builder after converting into String using toString() method.

5. Conclusion


in this article, We've seen what is String API replace() method. Implemted exmaple programs on it.

Tested with multiple occurrence of char or string scenarios.

Further also dicussed indepth on how repeat() method works internally. Provided step by step easy tutorial.

Example code snippets shown in this article is available over GitHub.


0 Comments