How to replace characters and substring in Java? String.replace(), replaceAll() and replaceFirst() Example

One of the common programming tasks is to replace characters or substring from a String object in Java. For example, you have a String "internet" and you want to replace the letter "i" with the letter "b", how do you that? Well, the String class in Java provides several methods to replace characters, CharSequence, and substring from a String in Java. You can call replace method on the String, where you want to replace characters and it will return a result where characters are replaced. What is the most important point to remember is that the result object would be a new String object? 

Since String is immutable in Java, every time you perform an operation on String either replacement or removing white space from String, it generates a new String object. The good thing about these methods is that they support regular expression, which means you can specify a pattern and all the characters which match the pattern will be replaced. 

There are four overloaded method to replace String in Java :

  • replace(char oldChar, char newChar)
  • replace(CharSequence target, CharSequence replacement)
  • replaceAll(String regex, String replacement)
  • replaceFirst(String regex, String replacement)

Out of these, 2nd one which takes a CharSequence is added on Java 1.5. CharSequence is actually a super interface for String, StringBuffer and StringBuilder in Java, which means you can pass any of String, StringBuffer or StringBuilder Object as an argument to this replace method. 

The replaceFirst() and replaceAll() are very powerful and accepts regular expression. replaceFirst() only replace first match, while replaceAll replaces all matches with replacement String provided.



How to replace character or substring in Java? replace() example

In this Java tutorial, we will see How to replace characters and substring from String in Java. First example in this program replaces a character, i.e. it replaces "J" with "K", which creates "Kava" from "Java". Second String replace example, replaces words from String, it replaces Scala with Java. 

Third and fourth example shows how to use regular expression to replace String in Java. Both examples uses \\s to match spaces or any white space character and replace with #

How to replace characters on String in Java? String.replace(), replaceAll() and replaceFirst() Example


Third one uses replaceFirst() which only replace first match, while fourth one uses replaceAll() which replaces all matches.

package test;

/**
 * Java program to replace String in Java using regular expression.
 * This examples examples how to replace character and substring from String in Java.
 *
 * @author Javin Paul
 */
public class StringReplace {
 
    public static void main(String args[]) {

     String word = "Java";
    
     //replacing character in this String
     String replaced = word.replace("J", "K");
     System.out.println("Replacing character in String");
     System.out.println("Original String before replace : " + word);
     System.out.println("Replaced String : " + replaced);
    
     //replacing substring on String in Java    
     String str = "Scala is good programming language";
     replaced = str.replaceAll("Scala", "Java");
     System.out.println("String before replace : " + str);
     System.out.println("String after replace : " + replaced);
    
     //replacing all space in String with # using regular expression
     replaced = str.replaceFirst("\\s", "#");
     System.out.println("Replacing first match of regex using replaceFirst()");
     System.out.println("Original String before replacement : " + str);
     System.out.println("Final String : " + replaced);
    
     System.out.println("Replacing all occurrence of substring which match regex");
     replaced = str.replaceAll("\\s", "#");
     System.out.println("ReplaceAll Example : " + replaced);
    } 
   
}

Output:
Replacing character in String
Original String before replace : Java
Replaced String : Kava
String before replace : Scala is good programming language
String after replace : Java is good programming language
Replacing first match of regex using replaceFirst()
Original String before replacement : Scala is good programming language
Final String : Scala#is good programming language
Replacing all occurrence of substring which match regex
ReplaceAll Example : Scala#is#good#programming#language

That's it on How to replace String in Java. As explained java.lang.String class provides multiple overloaded methods, which can replace a single character or substring in Java. replaceAll() in particular is very powerful and can replace all occurrences of any matching character or regular expression in Java.

It also expects a regular expression pattern, which provides it more power. You can use this method to say replace all commas with pipe to convert a comma-separated file to a pile delimited String. If you just want to replace one character, just use replace() method, which takes two characters, the old and new characters. 


Related Java String Tutorials from Java67 Blog


4 comments:

  1. I am definitely going to attend the Java One again. Last time I had a chance to help people at NetBeans Booth, thanks to Java One Team for that great favor. I know, Java and NetBeans community will definitely attend this prestigious nd great conference this year too…..
    You all can Sign up here https://www.regpulse.com/javaone2013/register.php?pcode=737266&src=4003&Act=1 to find out more details and launch date for the 2013 JavaOne. JavaOne India 2013 goin to happen on 8-9 May in Hyderabad at the same place as last year guys….

    ReplyDelete
  2. absolutely amazing. Thanks :)

    ReplyDelete
  3. Hi, I just would like to ask. Is there any alternative in changing characters or words without using the replace function? Maybe using a loop and conditional statement? Thanks :)

    ReplyDelete
    Replies
    1. yes, you can replace by changing characters directly in character array, it will become problem of replacing character in array then.

      Delete

Feel free to comment, ask questions if you have any doubt.