$show=/label

Java String API replace() Method Example

SHARE:

Java W3schools Blog. Quick guide to Java String API replace() Method with Examples and Internal Implementation. Syntax: public String replace​(char oldChar, char newChar)

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.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java String API replace() Method Example
Java String API replace() Method Example
Java W3schools Blog. Quick guide to Java String API replace() Method with Examples and Internal Implementation. Syntax: public String replace​(char oldChar, char newChar)
https://1.bp.blogspot.com/-u8JVWBeO9SU/XPAu29oNQuI/AAAAAAAABn4/ZhSlRZCwHbIAQNgNCwmjOoUEYwL2Dj56gCLcBGAs/s320/Java%2BString%2BAPI%2Breplace%2528%2529%2BMethod%2BExample.PNG
https://1.bp.blogspot.com/-u8JVWBeO9SU/XPAu29oNQuI/AAAAAAAABn4/ZhSlRZCwHbIAQNgNCwmjOoUEYwL2Dj56gCLcBGAs/s72-c/Java%2BString%2BAPI%2Breplace%2528%2529%2BMethod%2BExample.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/java-string-replace.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/java-string-replace.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content